1.
var value1 = 0, value2 = 0, value3 = 0;
for (var i = 1; I <= 3; i++) {
var i2 = i;
(function () {
var i3 = i;
SetTimeout (function () {
Value1 + = i;
value2 + = I2;
Value3 + = i3;
}, 1);
})();
}
SetTimeout (function () {
Console.log (value1, value2, value3);
}, 100);
Find results and why
You can think of settimeout as a constant push into the code in an extra controller.
For inside the closures are all aware that closures are immediate execution of the value of the closure scope should maintain the current execution of the loop values such as I should be a three-to-three closure, but the closure of the package is settimeout
The settimeout is push to the extra controller. In this case, the current wheel execution is complete, release the CPU and then traverse the controller controller push three times settimeout code begins execution
The code begins to look for the value of the variable based on the scope of the storage time.
(Model reference event loop)--settimeout how to maintain scope = = Self Research
So the value of I in the settimeout is the final value of I after cyclic execution 4
I2 Note for the time to 3 i2=3; i++; i=4, at the end of the judgment i<=3 cycle
So
I2 Final value: 3.
Value1 12
value2 9
The most disgusting value3.
Doing this in a closure.
var i3 = i;
i3 the value output to the SetTimeout and released it.
The first time the loop executes the closure
I3=1
Second i3=2 the third time i3=3;
Corresponds to the corresponding settimeout push code is equivalent to
。。。
Value3+=1;
。。。
value3+=2;
。。。
value3+=3;
JS Topic set 16