考虑此:
var x = null;
function a() {
x = window.setTimeout(() => {
alert("hello")
})
}
a();
function b() {
window.clearTimeout(x);
alert("bye")
}
b();
上面的代码片段仅打印bye
,而不打印hello
。但是,如果仅在方法b
中重新分配x,则将同时打印hello
和bye
。机制是什么?
var x = null;
function a() {
x = window.setTimeout(() => {
alert("hello")
})
}
a();
function b() {
x = undefined;
window.clearTimeout(x);
alert("bye")
}
b();
“超时变量”只是一个数字,即超时的ID。重新分配分配给数字的变量本身并不是问题,但是如果要清除超时,则必须将相同的超时ID传递给clearTimeout
。只是为了说明,而不是您应该在真实代码中执行此操作,您可以在页面加载开始时调用setTimeout
并获得1的超时ID,然后用clearTimeout
调用1
,然后将清除超时:
x = window.setTimeout(() => {
alert("hello")
});
window.clearTimeout(1);
变量本身没有什么特别的,它只是您需要跟踪的value数字,以便可以将其传递给clearTimeout
。
在您的第二段代码中,因为您在执行undefined
之前先将x
分配给clearTimeout(x)
,所以解释程序不知道ID为undefined
的持续超时,因此它不会清除任何内容。
您还可以将超时ID号分配给different变量,并清除原始变量:
var x = null;
function a() {
x = window.setTimeout(() => {
alert("hello")
})
}
a();
function b() {
const savedX = x;
x = undefined;
window.clearTimeout(savedX);
alert("bye")
}
b();
这是因为window.clearTimeout(x);
首先调用并清除超时,因此没有hello
警报。
如果使用不带延迟参数的setTimeout
,它将执行下一个事件周期,这意味着在您的情况下执行b()
之后。
时间(以毫秒(千分之一秒)为单位,计时器应在执行指定的功能或代码之前等待。如果省略此参数,则使用值0,表示“立即”或更准确地执行下一个事件周期。请注意,无论哪种情况,实际延迟都可能比预期的要长;