Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop every five seconds in Javascript

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:

  1. Wait five seconds
  2. Execute
  3. Wait five seconds
  4. Execute
  5. Wait five seconds
  6. Execute
  7. 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/

like image 838
Chuck Le Butt Avatar asked Oct 22 '25 23:10

Chuck Le Butt


1 Answers

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

like image 200
astian Avatar answered Oct 25 '25 12:10

astian