[英]clearTimeout() inside setTimeout() method not working in JS
setTimeout()
方法中的clearTimeout()
在JavaScript中不起作用
var c = 0;
var t;
function timedCount() {
document.getElementById('txt').value = c;
c = c + 1;
if (c == 5) {
clearTimeout(t);
}
t = setTimeout(function () {
timedCount()
}, 1000);
}
您需要阻止執行其余代碼,實際上您在清除setTimeout
后重新聲明了t
。 小提琴
var c = 0;
var t;
function timedCount() {
document.getElementById('txt').value = c;
c = c + 1;
if (c == 5) {
clearTimeout(t);
return false;
}
t = setTimeout(timedCount, 1000);
}
或者只使用else
語句:
if (c == 5) {
clearTimeout(t);
// do something else
}else{
t = setTimeout(timedCount, 1000);
}
當你調用clearTimeout
時,永遠不會有超時清除,因為最后一個已經被觸發,而下一個尚未設置。
你想改變你的邏輯,以便if (c !== 5) { setTimeout(etc etc) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.