[英]javascript setTimeout() is not working after few minutes and then it resolves without delay
我为 60 秒的计时器编写了一个代码,但 setTimeout() 可以正常执行几分钟,但一段时间后它正在解决 function 但没有延迟,并且 function 每秒都得到解决。
在这里, this.rateCardTimerText 在第一次调用中初始化为零。
如果可用,请提供任何适当的解决方案,或者是否有任何替代方法来实现它,然后请提及。
onChangeTimerChangeInfinity() {
let no = Number(this.rateCardTimerText)
if (no >= 100) {
no = 0
this.getCurrencyList()
}
else {
no += 1.66
}
this.rateCardTimerText = no
this.forceUpdate()
setTimeout(this.onChangeTimerChangeInfinity.bind(this), 1000)
}
确保在每次运行时清除之前的 setTimeout,如下所示:
let intervalObj;
onChangeTimerChangeInfinity() {
clearTimeout(intervalObj)
let no = Number(this.rateCardTimerText)
if (no >= 100) {
no = 0
this.getCurrencyList()
}
else {
no += 1.66
}
this.rateCardTimerText = no
this.forceUpdate()
intervalObj = setTimeout(this.onChangeTimerChangeInfinity.bind(this), 1000)
}
此外,就像上面的setInterval()
选项一样,您最终可能会导致代码自己跳闸,因为无论如何您都在强制这个东西每秒触发一次。 如果getCurrencyList()
或forceUpdate()
是async
,请考虑将第二个 function 重写为 promise,然后类似于:
let intervalObj;
onChangeTimerChangeInfinity() {
clearTimeout(intervalObj)
doAsyncStuffInPromise().then( () => {
intervalObj = setTimeout(this.onChangeTimerChangeInfinity.bind(this), 1000)
})
}
请改用setInterval()
。
setInterval( () => onChangeTimerChangeInfinity, 1000);
onChangeTimerChangeInfinity() {
let no = Number(this.rateCardTimerText);
if (no >= 100) {
no = 0;
this.getCurrencyList();
}
else {
no += 1.66;
}
this.rateCardTimerText = no;
this.forceUpdate();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.