Languages
[Edit]
EN

JavaScript - delay iterations in the loop

0 points
Created by:
Adnaan-Robin
274

In this article, we would like to show you how to delay iterations in the loop in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

for (let i = 0; i < 5; i++) {
  forLoopBody(i, 1000);
}

function forLoopBody(iteration, delay) {
  setTimeout(() => {
    console.log('for loop iterating...');  // loop body here
  }, delay * iteration);
}

 

Practical example

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 below example we create such function and put simple console.log() as a loop body inside. We also set delay of each iteration to 1000 milliseconds (1 second).

Runnable example:

// ONLINE-RUNNER:browser;

for (let i = 0; i < 5; i++) {
  forLoopBody(i, 1000);
}

function forLoopBody(iteration, delay) {
  setTimeout(() => {
    console.log('for loop iterating...');  // loop body here
  }, delay * iteration);
}

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.

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