1 回答
TA贡献2021条经验 获得超8个赞
在创建计时器之前,您不能直接传递计时器的 ID。问题是你必须调用 setInterval
才能获取 ID,然后才能将其实际传递给被调用的函数:
let timerId = setInterval(function() {}, 1000, timerId); //error - we are using `timerId` before its declaration is finished
传递一个对象
但是,您可以利用对象在共享相同引用的情况下工作的方式。因此,您可以初始化一个对象,这意味着该变量存在,然后调用setInterval并将计时器ID记录为该对象的属性。然后将该对象作为参数传递给回调。当回调执行时,对象属性肯定会被填充,您可以只使用其中的值:
let cb;
{ //callback in one scope
//simple counter that stops at zero
let i = 3;
cb = timerContext => {
console.log(i--);
if (i < 0) {
console.log("finish");
clearInterval(timerContext.timerId);
}
}
}
{//start the timer in a different scope
let context = { timerId: null };
context.timerId = setInterval(cb, 1000, context);
}
创建一个包装器
或者,如果您在调用 setInterval 时为其创建包装函数,则只能向外部回调传递计时器 ID:
let cb;
{ //callback in one scope
//simple counter that stops at zero
let i = 3;
cb = timerId => {
console.log(i--);
if (i < 0) {
console.log("finish");
clearInterval(timerId);
}
}
}
{//start the timer in a different scope
let timerId = setInterval(() => cb(timerId), 1000);
}
传递为this
this
如果您愿意,如果您的回调是普通函数,则可以以任一方式将计时器 ID 作为上下文传递:
目的
let cb;
{ //callback in one scope
//simple counter that stops at zero
let i = 3;
cb = function() {
console.log(i--);
if (i < 0) {
console.log("finish");
clearInterval(this.timerId);
}
}
}
{//start the timer in a different scope
let context = { timerId: null };
context.timerId = setInterval(cb.bind(context), 1000);
}
只要身份证号
let cb;
{ //callback in one scope
//simple counter that stops at zero
let i = 3;
cb = function() {
console.log(i--);
if (i < 0) {
console.log("finish");
clearInterval(this);
}
}
}
{//start the timer in a different scope
let timerId = setInterval(() => cb.call(timerId), 1000);
}
添加回答
举报