I'm trying to write a simple loop in JS (or JQuery) that updates an image every five seconds, for a total of 15 seconds (so three loops), and then quits.
It should go like this:
But setTimeout only seems to work once.
As a test, I've tried:
function doSetTimeout(i) {
setTimeout(function() { alert(i); }, 5000);
}
for (var i = 1; i <= 5; ++i)
doSetTimeout(i);
Does not work: http://jsfiddle.net/ubruksco/
I've also tried:
for(var i = 1; i <= 5; i++) {
(function(index) {
setTimeout(function() { alert(index); }, 5000);
})(i);
}
Does not work: http://jsfiddle.net/Ljr9fq88/
var time = 1;
var interval = setInterval(function() {
if (time <= 3) {
alert(time);
time++;
}
else {
clearInterval(interval);
}
}, 5000);
you can simply create an interval and kill it after the 3rd time
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With