Languages
[Edit]
EN

TypeScript - delay iterations in the loop

0 points
Created by:
Rian-Whitehouse
469

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 * iteration as a setTimeout argument to delay each iteration. If you use just delay only the first iteration will be delayed.

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join