How to implement delayed execution in a JavaScript loop?
P粉680000555
2023-08-20 14:12:51
<p>I want to add a delay/sleep in a <code>while</code> loop: </p>
<p>I tried the following: </p>
<pre class="brush:php;toolbar:false;">alert('hi');
for(var start = 1; start < 10; start ) {
setTimeout(function () {
alert('hello');
}, 3000);
}</pre>
<p>Only the first case is correct: after displaying <code>alert('hi')</code>, it will wait for 3 seconds and then display <code>alert('hello' )</code>, but then <code>alert('hello')</code> will be displayed repeatedly. </p>
<p>What I want is that after 3 seconds of showing <code>alert('hello')</code>, it needs to wait another 3 seconds before showing <code>alert(' hello')</code>, and so on. </p>
Since ES7, there is a better way to waitloop:
When the engine reaches the
await
section, it sets a timeout and pauses execution of theasync function
. Then, when the timeout completes, execution continues at that point. This is very useful because you can defer (1) nested loops, (2) conditionals, (3) nested functions:Reference materials on MDN
Although ES7 is now supported by NodeJS and modern browsers, you may want to transpile it with BabelJS to run everywhere.
setTimeout()
The function is non-blocking and returns immediately. So your loop iterates very quickly and triggers the 3 second timeout in quick succession. That's why your first alert pops up after 3 seconds and all other alerts follow continuously without any delay.You may want to use code similar to: