gpt4 book ai didi

javascript - 递归 setTimeout - 不是变量

转载 作者:行者123 更新时间:2023-12-03 05:01:52 25 4
gpt4 key购买 nike

我想制作一个计时器,从某个初始数字开始倒计时,并在为零时停止。

我最初使用 setInterval 来完成此操作,但我想将计时器 (setInterval) 与倒计时函数分开,并且发现很难终止 setInterval。

我目前正在尝试使用 setTimeout 来实现相同的目标,该 setTimeout 有条件地再次调用相同的 setTimeout,但它不起作用。

function Timer(initialTime) {
this.time = initialTime;
this.tickTock = null
}

Timer.prototype.countDown = function() {
if (this.time <= 0) {
clearTimeout(this.tickTock);
} else {
console.log(this.time);
this.time--;
this.proceed();
}
}

Timer.prototype.proceed = function() {
this.tickTock = setTimeout(this.countDown, 3000);
}

var timer = new Timer(10);
timer.proceed();

调用timer.proceed()时,出现错误:

TypeError: this.proceed is not a function

at Timer.countDown [as _onTimeout]

如何在 countDown 函数中引用proce函数?

最佳答案

回调setTimeout未绑定(bind)到您的对象,但它绑定(bind)到 window因此thiswindow对象不是你的timer目的。您可以使用 Function.prototype.bind 绑定(bind)回调像这样:

this.tickTock = setTimeout(this.countDown.bind(this), 3000);

注意:使用setTimeout时不需要this.tickTock ,您可以通过不调用另一个 proceed 来停止倒计时。你可以保留它,但它没有任何用处。 (请参阅下面的代码片段)。

工作代码片段:

function Timer(initialTime) {
this.time = initialTime;
}

Timer.prototype.countDown = function() {
if (this.time <= 0) { // if the counter is less or equal 0, return and don't call proceed
return;
}
// otherwise continue
console.log(this.time);
this.time--;
this.proceed();
}

Timer.prototype.proceed = function() {
setTimeout(this.countDown.bind(this), 1000);
}

var timer = new Timer(10);
timer.proceed();

关于javascript - 递归 setTimeout - 不是变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42192310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com