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:
- Wait five seconds
- Execute
- Wait five seconds
- Execute
- Wait five seconds
- Execute
- Quit
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/