0

While test the settimeout function of Nodejs, Put settimeout in two for loops ,if both the for loops have the same variables name i, It seems to be that the two settimeout functions are sharing the variable.

code:

for (var i = 1; i <= 3; i++) { 
    var tm1=setTimeout(function(){
         console.log(i); 
            }, 0); 
}
for (var i = 1; i <= 4; i++) {
    (function (x) {
        var tm2=setTimeout(function () { console.log(x); }, 100);
    })(i);
}

Result: 6 6 6 1 2 3 4 5
If the for loops have different variables name n and i, the results look all right

code:

for (var n = 1; n <= 3; n++) { 
    //change the variable name from i to n
    setTimeout(function(){
         console.log(n); 
            }, 0); 
}
for (var i = 1; i <= 5; i++) {
    (function (x) {
        var tm2=setTimeout(function () { console.log(x); }, 100);
    })(i);
}

Result: 4 4 4 1 2 3 4 5

How to understand this?

GuRu
  • 1,880
  • 3
  • 23
  • 32
sylarmeng
  • 3
  • 1

1 Answers1

1

There is only function scope and no block scope in ES5. Your observation has nothing to do with the setTimeout function but with the javascript variable scope

read here

jahnestacado
  • 593
  • 3
  • 9