How to use setTimeout inside a for loop in JavaScript
In this tutorial, we are going to learn about the how can we use setTimeout method inside a for loop in JavaScript with the help of examples.
for loop
Let’s see what happens when we add a setTimeout
method inside a for loop.
for (var i=0;i<5;i++){
setTimeout(function(){
console.log(i);
}, 1000);
}
//---> Output 5,5,5,5,5
After 1000
milliseconds we will see a 5
is logged inside browser console but we need 0,1,2,3,4
this happens because of JavaScript is executing the code in synchronous fashion(it means one line after another) but setTimeout
method is asynchronous so that JavaScript runs the asynchronous code once the synchronous code execution is completed.
At the time of synchronous code (for loop) execution is completed the variable i
value is 5
so that we can see 5
inside our console.
Using let keyword
The problem can be solved by using an es6 let
keyword because it creates a new variable on each iteration but var
keyword is using the same variable throughout the for loop
execution.
for (let i=0;i<5;i++){
setTimeout(function(){
console.log(i);
}, 1000);
}
// -- > output 0,1,2,3,4
Using IIFE function
If you don’t like using es6 let
keyword, we can also solve the problem by using immediately invoked function expression (IIFE).
Example:
for (var i = 0; i < 5; i++) {
(function(val) { //val is parameter
setTimeout(function() {
console.log(val);
}, 1000);
})(i); // i is argument
}
// -- > output 0,1,2,3,4
In the above code, on each iteration the function
is invoked by itself a var i
is passed an argument to the function so that we can see the expected output because on each iteration the variable i
is holding a different value.
Using functions
for (var i = 0; i < 5; i++) {
function timeout(val) {
setTimeout(function() {
console.log(val);
}, 1000);
}
timeout(i);
}