Why does the following javascript log 3
3 times instead of 0
, 1
, and 2
?
for (var i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i);
}, 42);
}
For each iteration, shouldn't a new function be created based on the value of i
for that iteration? And then that function is passed as an argument to setTimeout
?