I don't understand how to explain the below code and why it does not work as intended:
for (var i = 0; i < 16; i++) {
setTimeout(function () {
console.log(i);
}, 1)
}
// Prints "16" 16 times
One solution to this would be simply using let
instead of var
in the for loop, or
for (var i = 0; i < 16; i++) {
(function (k) {
setTimeout(function () {
console.log(k);
}, 100)
})(i)
}
// Print "0" to "15"
a self invoking function.
If I could have an educated guess to this it would be that var's scope is tied to the function block, or in the case the global scope, and the for loops will beat the call stack that the setTimeout()
will produce and since Javascript is lexically scoped it calls back all these functions as var i = 16
where on the other hand let i = 16
will keep it to the block?