[英]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.