How to Output with setTimeOut() inside a Loop

Apr 11, 2018
for( var i = 0;  i < 5;  i++ ) {

    setTimeout(function() {

        console.log( i );

    }, 1000 * i)

}

 

What is the result, what causes this problem, how to solve this problem?

 

Answer:

This will output 5 in each second, and will output 5 times in total.

This problem is caused by the variable’s scope. If we just pass the “i” into the setTimeout, the setTimeout will share the same variable. And we know, the for loop takes almost no time to finish. So when the setTimeout runs, the “i” is already finished in the for loop, which will set the “i” to 5. Thus, each setTimeout will output 5.

If we pass the “i” to the function, it will remember the i each time from  the loop as a local variable.

This can be solved by passing the “i” as a function’s parameter.

 

for( var i = 0; i < 5; i++ ) {

    setTimeout(function(j) {

        console.log(j);

    }, 1000*i, i)

}