(function test() {
for (var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i)
, 100});
}
})();
Expected return would be
0
1
2
3
4
5
6
7
8
9
Actual return is
10
10
10
10
10
10
10
10
10
10
That happened because of setTimeout function, which receives the value after updating variable "i" 10 times.
It is to nest setTimeout function with self-invoking function, so you can pass the "i" value of each cycle moment to it!!
(function test() {
for (var i = 0; i < 10; i++) {
(function(i) {
setTimeout(function() {
console.log(i);
}, 1000);
})(i);
}
})();
The result would be
0
1
2
3
4
5
6
7
8
9
In ES6,
You can only change "var" to "let" in for loop parenthesis, because "let" is scoped to the nearest enclosing block.
(function test() {
for (let i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i)
, 100});
}
})();
Cool!!