Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - setTimeout() / clearTimeout()

Tags:

javascript

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);
    }
})();
like image 634
Ekil Avatar asked Apr 14 '26 16:04

Ekil


1 Answers

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);
  }
})();
like image 78
CertainPerformance Avatar answered Apr 16 '26 06:04

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!