/* What will the following code output? */
for (var i = 0; i < 3; i++) {
setTimeout(function() { alert(i); }, 1000 + i);
}
/* ANSWER */
/*
it will show - 3, 3, 3.
But we expect: 0, 1, 2.
one way to solve the problem is immediately executable function
for (var i = 0; i < 3; i++) {
setTimeout(function(i_local) {
return function() { alert(i_local); }
}(i), 1000 + i);
}
или лучше просто использовать let вместо var.
for (let i = 0; i < 3; i++) {
setTimeout(function() { alert(i); }, 1000 + i);
}
*/