Why does this function print out 0 1 2 instead of 0 1 2 3?
(function fn1(){
for (var i = 0; i < 4; i++) {
var tc=setTimeout(function(i){
console.log(i);
clearTimeout(tc);
}, 10, i);
}
})();
var gets hoisted, of course, so in the for loop tc gets (synchronously) reassigned multiple times and ends up as the final setTimeout. So, each time the timeout function runs, it references the same tc that references the final iteration's timeout and clears it with clearTimeout. To the interpreter, it looks like this:
(function fn1() {
var tc;
var i;
for (i = 0; i < 4; i++) {
tc = setTimeout(function(i) {
console.log(i);
clearTimeout(tc);
}, 10, i);
}
})();
If you wanted to print out 0 1 2 3, use let instead (let has block scope, and is not hoisted) to give each iteration a separate binding for tc:
(function fn1() {
for (let i = 0; i < 4; i++) {
let tc = setTimeout(function(i) {
console.log(i);
clearTimeout(tc);
}, 10, i);
}
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With