Guber Jan Guber Jan - 3 months ago 13
Javascript Question

Why I can't read the change of global variables in a nested function?

//this is a code question about nested functions and timer function



var num = 0; //the key of this problem
var timer = null;
timer = setInterval(function() {
//num could change from 0 to 9 in this function
console.log(num);
setTimeout(function() {
console.log(num); //but in this place, num is always 0,why?
}, 2000);

num++;
if (num >= 10) {
num = 0;
clearInterval(timer);
}
}, 100);




Answer

Why I can't read the change of global variables in a nested function?

You are. It's just a logic error, by the time your setTimeout callbacks occur, you've set it back to 0: You increment num every 100ms, setting it to 0 when it reaches 10 and then stopping the increment process. After 2000ms, you show the value of num. At that point, it's going to be 0, because it reached 0 after 10 loops at 100ms intervals, a second earlier.

Put another way, here's what happens:

  1. Time 0ms: You set num to 0
  2. Time 0ms: You set up a repeating interval timer (setInterval) at 100ms
  3. Time ~100ms: The interval fires the first time:
    1. It sets up the first callback for 2000ms later
    2. Changes num to 1
  4. Time ~200ms: The interval fires the second time:
    1. It sets up the first callback for 2000ms later
    2. Changes num to 2
  5. That happens again at ~300ms (num -> 3), ~400ms (num -> 4), ~500ms (num -> 5), ~600ms (num -> 6), ~700ms (num -> 7), ~800ms (num -> 8), ~900ms (num -> 3)
  6. Time ~1000ms: The interval fires the last time:
    1. It sets up yet another callback for 2000ms later
    2. It sets num to 10, then to 0 and cancels the interval
  7. Time ~2100ms: The first setTimeout callback fires, showing num = 0
  8. Time ~2200ms: The second setTimeout callback fires, showing num = 0
  9. ...and so on