Wednesday 3 August 2016

javascript - Why does this for / setTimeout() code actually output the numbers from 0 to 9?

A common pitfall with JavaScript closures is running setTimeout() from a for loop, and expecting the counter to be passed with different values at each iteration, while in practice it gets assigned the last value before the setTimeout() functions execute:





for (i = 0; i < 10; i++) {
setTimeout(function () {
console.log(i)
}, 100);
} // => prints "10" 10 times






One solution to this is to have an Immediately Invoked Function Expression:





for (i = 0; i < 10; i++)
(function(j) {
setTimeout(function foo() {

console.log(j)
}, 100);
})(i); // prints 0, 1, 2, 3, 4, 5, 6, 7, 8, 9





Another is to pass an extra callback argument to setTimeout() (which doesn't work in IE<9):






for (i = 0; i < 10; i++) {
setTimeout(function foo(n) {
console.log(n)
}, 100, i);
}






But why does the following, simplest, code, produce the same result (0, 1, 2, ... 9)?





for (var i = 0; i < 10; i++)
setTimeout(console.log(i), 100);


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...