The following alerts 2 every time.
function timer() {
for (var i = 0; i < 3; ++i) {
var j = i;
setTimeout(function () {
alert(j);
}, 1000);
}
}
timer();
Shouldn't var j = i; set the j into the individual scope of the setTimeout?
Whereas if I do this:
function timer() {
for (var i = 0; i < 3; ++i) {
(function (j) {
setTimeout(function () {
alert(j);
}, 1000);
})(i);
}
}
timer();
It alerts 0, 1, 2 like it should.
Is there something I am missing?
jis not initialized in the scope ofsetTimeoutbut in the scope oftimerfunction, whereas in the second example you create an anonymous function, where you passi, implicitly initialisingjin the scope of closure. This creates and executes 3 functional blocks, setting 3 timeouts at once.