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); };
What you want is closer to this: var i = 0; function nextFrame() { if(i < n) { someanimation(); i++; // Continue the loop in 3s setTimeout(nextFrame, 3000); } } // Start the loop setTimeout(nextFrame, 0);
To create pause or delay in a JavaScript for loop, we should use await with a for-of loop. to define the wait function that returns a promise that calls setTimeout with resolve to resolve the promise in ms milliseconds. Then we define the loop function that runs a for-of loop to loop through an array.
The standard way of creating a delay in JavaScript is to use its setTimeout method. For example: console. log("Hello"); setTimeout(() => { console.
Just put the timeout in the for-loop, and the loop is less fast: When we run the code with setTimeout, the following happens: nothing happens for 1 second; then all the logs come up in a flash. Not really what we had hoped for.
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);
setTimeout
is a little trickier than that because it doesn't block (i.e. it doesn't finish waiting on the timeout before continuing with the program).
What you want is closer to this:
var i = 0; function nextFrame() { if(i < n) { someanimation(); i++; // Continue the loop in 3s setTimeout(nextFrame, 3000); } } // Start the loop setTimeout(nextFrame, 0);
It may also be worth your while to read up on setInterval
as a possible alternative.
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