为什么我无法读取嵌套函数中全局变量的变化?
Why I can't read the change of global variables in a nested function?
//这是一道关于嵌套函数和timer函数的代码题
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);
Why I can't read the change of global variables in a nested function?
你是。这只是一个逻辑错误,当您的 setTimeout
回调发生时,您已将其 back 设置为 0:您每 100 毫秒递增 num
,将其设置为当达到 10 时为 0,然后停止递增过程。 2000 毫秒后,显示 num
的值。到那时,它将为 0,因为它以 100 毫秒的间隔循环 10 次后达到 0,早一秒。
换句话说,情况是这样的:
- 时间 0 毫秒:您将
num
设置为 0
- 时间 0 毫秒:您将重复间隔计时器 (
setInterval
) 设置为 100 毫秒
- 时间~100ms:第一次触发的时间间隔:
- 它设置了 2000 毫秒后的第一个回调
- 将
num
更改为 1
- 时间~200ms:间隔触发第二次:
- 它设置了 2000 毫秒后的第一个回调
- 将
num
更改为 2
- 再次发生在 ~300ms (num -> 3), ~400ms (num -> 4), ~500ms (num -> 5), ~600ms (num -> 6), ~700ms (num - > 7), ~800ms (num -> 8), ~900ms (num -> 3)
- Time ~1000ms: 最后一次触发的时间间隔:
- 它在 2000 毫秒后设置了另一个回调
- 设置num为10,然后为0,取消间隔
- 时间 ~2100 毫秒:第一个
setTimeout
回调触发,显示 num = 0
- 时间 ~2200ms:第二个
setTimeout
回调触发,显示 num = 0
- ...等等
//这是一道关于嵌套函数和timer函数的代码题
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);
Why I can't read the change of global variables in a nested function?
你是。这只是一个逻辑错误,当您的 setTimeout
回调发生时,您已将其 back 设置为 0:您每 100 毫秒递增 num
,将其设置为当达到 10 时为 0,然后停止递增过程。 2000 毫秒后,显示 num
的值。到那时,它将为 0,因为它以 100 毫秒的间隔循环 10 次后达到 0,早一秒。
换句话说,情况是这样的:
- 时间 0 毫秒:您将
num
设置为 0 - 时间 0 毫秒:您将重复间隔计时器 (
setInterval
) 设置为 100 毫秒 - 时间~100ms:第一次触发的时间间隔:
- 它设置了 2000 毫秒后的第一个回调
- 将
num
更改为 1
- 时间~200ms:间隔触发第二次:
- 它设置了 2000 毫秒后的第一个回调
- 将
num
更改为 2
- 再次发生在 ~300ms (num -> 3), ~400ms (num -> 4), ~500ms (num -> 5), ~600ms (num -> 6), ~700ms (num - > 7), ~800ms (num -> 8), ~900ms (num -> 3)
- Time ~1000ms: 最后一次触发的时间间隔:
- 它在 2000 毫秒后设置了另一个回调
- 设置num为10,然后为0,取消间隔
- 时间 ~2100 毫秒:第一个
setTimeout
回调触发,显示 num = 0 - 时间 ~2200ms:第二个
setTimeout
回调触发,显示 num = 0 - ...等等