Skip to content

JavaScript setTimeout loop | Example code

  • by

To execute JavaScript setTimeout in loop do print each time on setTimeout callback execution. The setTimeout function callback isn’t triggered until the for loop execution has completed.

for(var i = 0;i < 5; i++){
    setTimeout(function(){
        console.log('count ', i);
    }, 3000);
}

hen the for loop has finished executing the value of i is 5. Now when the setTimeout call begins to execute it uses the last set value of i which is 5. Hence 5 is printed in all the setTimeout callbacks.

JavaScript setTimeout loop

Simple example the loop waits for 3000 milli-seconds initially and then executes the whole for loop at once.

<!DOCTYPE html>
<html>
<body>
  <script>

    var array = [1, 2, 3, 4, 5];
    
    for(let i = 0; i < array.length; i++) {
      setTimeout(() => {
        console.log(array[i])
      }, 1000);
    }
  </script>

</body>
</html> 

Another example where each iteration is called after waiting for 1000 milli-seconds.

<script>
    var array = [1, 2, 3, 4, 5];

    for (var i=0; i<array.length; i++) {
     (function(ind) {
      setTimeout(function(){console.log(array[ind]);}, 1000 * ind);
     })(i);
   }
</script>

Output:

JavaScript setTimeout loop

1. setTimeout Inside For Loop Using IIFE (Immediately Invoked Function Expression)

Use IIFE to create a new scope for each setTimeout callback without polluting the global scope. Simply wrap up the setTimeout code inside a IIFE. Here is how it looks:

// setTimeout inside for loop with IIFE Wrapper

for(var i = 0; i < 5; i++){
    (function(i){
        setTimeout(function(){
            console.log('value is ', i);
        }, 3000);
    })(i);
}

2. setTimeout Inside For Loop Using let Keyword

he let keyword creates a separate scope for each iteration making it possible to print the consecutive variable value. Here is how the code looks:

// setTimeout inside For loop Using let keyword
for(var i = 0;i < 5; i++){
    let k = i;
    setTimeout(function(){
        console.log('count ', k);
    }, 3000 * (k + 1));
}

Execute the above piece of code and you will be able to view the numbers from 0 to 4 printed in the browser console.

Do comment if you have any doubts or suggestions on this JS set Timeout topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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