Create a pause inside a while loop in javascript

djianp picture djianp · Dec 28, 2010 · Viewed 65.6k times · Source

I would like to create a pause inside a while loop so that I can create n animations that each appear 3 seconds after the other.

I've tried the following, but it doesn't work. Would love to have someone show me what I'm doing wrong. Thanks!!

i=0;
while (i < n) {
    someanimation();
    setTimeout(function(){
        i++;
    }, 3000);

};

Answer

Karl Knechtel picture Karl Knechtel · Dec 28, 2010

setTimeout does not pause; it asks Javascript to run some other code later.

Googling for "setTimeout loop" tells you exactly what you need to know. If you look around a little bit, it even mentions setInterval. The difference: using setTimeout to loop will wait 3 seconds in between loops, whereas setInterval will make it take 3 seconds total for the loop (including however much time the animation takes, as long as it's less than 3 seconds :) ). Also, setInterval constructs an infinite loop that you'll have to break out of after the desired number of times; setTimeout requires you to construct the loop yourself.

i = 0;

function animation_loop() {
  someAnimation();
  setTimeout(function() {
    i++;
    if (i < n) {
      animation_loop();
    }
  }, 3000);
};
animation_loop();

i = 0;
someAnimation();
setInterval(function() {
  i++;
  if (i < n) {
    someAnimation();
  }
}, 3000);