How to add a delay in a JS loop

JavaScript (JS) loops perform iterations through your code until a certain condition is met. The while, for, and do while loops are used to execute the condition. Depending on the task being executed, you might need to add a delay to the loop. This becomes possible by adding the setTimeout() method in JavaScript.

In this Answer, we will cover how to add a delay in a JS loop after every iteration and how to add an instant delay only at the start of the loop.

Let's use the setTimeout() method to add a 3 seconds delay in a while loop:

Example 1

let i = 0;
while (i<5) {
loop(i);
i++
}
function loop(i){
setTimeout(function(){
console.log(i);
}, 3000 * i)
}

In the above code, we execute a loop that iterates from 0–4. However, the function below the loop calls the setTimeout() method to execute our variable after a 3 seconds delay on every iteration.

Below is an example of a 4 seconds delay added to a for loop:

Example 2

for (let people = 8; people<12; people++) {
project(people)
}
function project(people) {
setTimeout(function(){
console.log(people);
}, 4000 * people );
}

The same concept will also be applied in a do while loop as shown below:

Example 3

let i = 3;
do {
loop(i);
i++;
} while (i < 6);
function loop(i){
setTimeout(function(){
console.log(i);
}, 4000 * i);
}

In the above code, the loop will always iterate to the next number after every 4 seconds as an output of the setTimeout() method.

How to add an instant delay only at the start of the loop

Adding an instant delay at the start of every loop will only require a time stamp without multiplying our variable with the milliseconds.

An example of an instant delay with the for loop is shown below:

for (let people = 8; people<12; people++) {
project(people)
}
function project(people) {
setTimeout(function(){
console.log(people);
}, 4000 );
}

In the above case, there will be an initial delay of 4 seconds before the first iteration, after which all the other numbers will appear instantly.

Conclusion

JavaScript allows developers to add delays in loops using the setTimeout() method. This comes in handy when we need to allow for a time lag between the iterations in our loops.

Copyright ©2024 Educative, Inc. All rights reserved