SetTimeout problem in the for loop

// for loop 1
for (var i = 0; i < 3; i++) {
    setTimeout(function () {
        console.log(i);
    },0);
}
// for loop 2
for (var i = 0; i < 3; i++) {
    setTimeout(function  (a) {
        console.log(a);
    }(i),0);
}
// The output is: 0,1,2,3,3,3

he output may cause you to question two points:
1) the delay time is also 0, so why execute the following for loop first?
2) why does the for loop at loop 1 output 3 and the for loop at loop 2 be 0, 1, 2?

q&a:
1) the delay time is also 0, so why execute the following for loop first?

function  (a) {
    console.log(a);
}(i)

The function is followed by () indicates that it is an immediate execution function, which is executed when the setTimeout function is called, rather than waiting for the timer to reach the point; and setTimeout(fn,0) is not executed immediately, but only means that the next time the event loop arrives can be executed
immediately Note: The setTimeout bound callback function is just a timer registered with Javascript’s event loop mechanism. This timer can only be executed in the next event loop of the current event loop.

2) why does the for loop at loop 1 output 3 and the for loop at loop 2 be 0, 1, 2?

for (var i = 0; i < 3; i++) {
   setTimeout(function  () {
        console.log(i);
    },0);
}
// equal
var i;// code line 1
for (i = 0; i < 3; i++) {
    setTimeout(function  () {
        console.log(i);
    },0);
}

Because the variable declared by var acts on the scope of the function, the variable i in the function points to the variable declared at line 1 of the code, and the value of i at the end of the for loop is 3, so when setTimeout is executed, the value of the variable i is already 3, and the output result is 3.
The function in setTimeout at loop 2 is an immediate execution function, and does not wait for the timer to reach the point before executing; the immediate execution function in setTimeout can be regarded as an ordinary function outside of setTimeout, so the output result is unexpected.

Leave a Reply