I'm having problems writing a script in jQuery.
I have an iFrame
in my page that needs to change.
The source of the iframe has to be http://www.example1.com
for ONE minute and then switched to http://www.example2.com
for FIVE minutes. This in a constant loop. But how can I do this?
I now have:
jQuery(document).ready(function () {
setTimeout(function() {
if($('#iframe').attr('src') == "http://www.example1.com")
{
$('#iframe').attr('src',"http://www.example2.com");
}
else
{
$('#iframe').attr('src',"http://www.example1.com");
}
}, 10000);
});
But this doesn't do so much. And it only runs once ..
Set initial
src
of iframe ashttp://www.example1.com
and ...This code prepares two timeouts, with one callback function executed after 1 minute and second callback executed after 1 + 5 = 6 minutes. Second callback 'rearms' these two timeouts and so on..
If you do not want to setup initial
src
, the code can be written asI believe this will work. Each time one of the functions is called, it sets a new timeout for the other function. You initally show 1, then set a 1 minute timeout. When that timeout expires, 2 is shown and a new timeout is set for 5 minutes, at which point, 1 will be shown again.
You could also create one interval callback that checks every 100ms if it's time to show the next content. Maybe it's a bit more complicated than the other approaches.
But if you include this as an external script it's only 3 lines of code to load what you want.
As alternative to an iframe you could also load the external file into an object tag. I have used it in the demo below. You can also find the same code as jsFiddle here.
If you prefer the iframe I have added the code for it in the loadData function as comment.
(I've set the time in the demo to 1 minute for each content but this can be changed as you like.)