setTimeout inside a for loop in JavaScript

In this tutorial, I will show how you can use setTimeout inside a for loop in JavaScript. Sometimes you may need to perform an action after a certain period of time has passed, you can use setTimeout to achieve this purpose.

In JavaScript, the setTimeout method is used to execute a function or specified block of code after a certain amount of time. It can be used to create a delay before executing a function. This can also be used to delay each loop iteration. It takes two parameters, a function or a string of code to be executed and the delay in milliseconds.

Here in the program below, I have used the setTimeout method inside a for loop.

// Created a for loop 
for (let i = 0; i < 5; i++) {
  // Delay each iteration by 1 second
  setTimeout(function() { 
    console.log(i); 
  }, 1000 * i, i); 
}

In the above program, each value of i in the for loop will be logged one second after the previous one.

The output of the above program would be like the below.

0
1
2
3
4

setTimeout Inside For Loop Using IIFE

IIFE stands for Immediately Invoked Function Expression. This function executes immediately after being defined. It is helpful for running code asynchronously or in a certain context. This function is often used to create a scope for variables that would otherwise be global.

Here’s the program below.

// Created a for
for (let i = 0; i < 5; i++) {
  // Created an IIFE
  (function(i) {
    // Delay each iteration by 1 second
    setTimeout(function() {
      console.log(i);
    }, 1000 * i);
  })(i);
}

In the above program, I have used IIFE to create a new scope for each iteration of the loop. Each iteration will create a new function that will execute after 1 second (1000 * i).

The value of `i` is passed as an argument to the function, ensuring that the correct value is logged.

The result will be the numbers 0 to 4 logged one second after the previous one.

Output:

0
1
2
3
4

Also read: Time Events in JavaScript with example – Create Stopwatch

Leave a Reply

Your email address will not be published. Required fields are marked *