EN
JavaScript - delay iterations in the loop
0 points
In this article, we would like to show you how to delay iterations in the loop in JavaScript.
Quick solution:
xxxxxxxxxx
1
for (let i = 0; i < 5; i++) {
2
forLoopBody(i, 1000);
3
}
4
5
function forLoopBody(iteration, delay) {
6
setTimeout(() => {
7
console.log('for loop iterating...'); // loop body here
8
}, delay * iteration);
9
}
To delay the loop iterations we need to:
- create a separate function with
setTimeout()
that actually delays the iterations, - move the loop body to the function inside the
setTimeout()
, - call the new function inside the loop.
In the below example, we create such function and put a simple console.log()
as a loop body inside. We also set the delay of each iteration to 1000
milliseconds (1 second).
Runnable example:
xxxxxxxxxx
1
for (let i = 0; i < 5; i++) {
2
forLoopBody(i, 1000);
3
}
4
5
function forLoopBody(iteration, delay) {
6
setTimeout(() => {
7
console.log('for loop iterating...'); // loop body here
8
}, delay * iteration);
9
}
Note:
We use
delay * iteration
as asetTimeout
argument to delay each iteration. If you use justdelay
only the first iteration will be delayed.