EN
TypeScript - delay iterations in the loop
0
points
In this article, we would like to show you how to delay iterations in the loop in TypeScript.
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.
Practical example
In the below example, we create the 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).
const forLoopBody = (iteration: number, delay: number): void => {
setTimeout((): void => {
console.log('for loop iterating...'); // loop body here
}, delay * iteration);
};
for (let i = 0; i < 5; i++) {
forLoopBody(i, 1000);
}
Note:
We use
delay * iterationas asetTimeoutargument to delay each iteration. If you use justdelayonly the first iteration will be delayed.