Skip to content
Advertisement

Create a pause inside a while loop in Javascript

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.

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

Advertisement

Answer

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;

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

// setInterval approach
i = 0;
someAnimation();
iid = setInterval(function() {
  i++;
  if (i < n) {
    someAnimation();
  } else {
    clearInterval(iid);
  }
}, 3000);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement