Reputation: 245
I'm trying to change the src of an iframe every 2 seconds with different page but I failed miserably so far. Can anyone tell me what's wrong with this code? It only loads the last file, 5.html and not the other ones, 1.html 2.html 3.html and 4.html
function reloadiframe(nbr) {
setTimeout(function () {
document.getElementById("iframe").src = nbr + ".html";
}, 2000);
}
function reload() {
for (i=1;i<=5;i++) {
reloadiframe(i);
}
}
Upvotes: 0
Views: 4183
Reputation: 66465
You're now delaying the reload for two seconds. Page 1, 2, 3 and 4 actually get loaded, but are quickly overwritten by frame 5.
Either use setTimeout
in reloadiframe
to delay the next reload, use setInterval
to periodically reload the iframe or increase the timeout:
function reloadiframe(nbr) {
document.getElementById("iframe").src = nbr + ".html";
if (n <= 5) {
setTimeout(function () {
reloadiframe(nbr + 1);
}, 2000);
}
}
function reload() {
setTimeout(function () {
reloadiframe(i);
}, 2000);
}
Alternative using setInterval
:
var timer, nbr;
function reloadiframe() {
document.getElementById("iframe").src = nbr + ".html";
if (nbr > 5) {
clearInterval(timer);
}
}
function reload() {
nbr = 1;
timer = setInterval(reloadiframe, 2000);
}
Upvotes: 2
Reputation: 359946
setTimeout
does not wait. The timeouts all fire at pretty much exactly the same time, since they are all started at pretty much exactly the same time. Just a small change will fix the problem:
function reloadiframe(nbr) {
setTimeout(function () {
document.getElementById("iframe").src = nbr + ".html";
}, 2000*i); // <== right here
}
function reload() {
for (i=1;i<=5;i++) {
reloadiframe(i);
}
}
Upvotes: 2