[英]clearTimeout() inside setTimeout() method not working in JS
clearTimeout()
inside setTimeout()
method not working in JavaScript 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);
}
You need to prevent the rest of the code of executing, actually you are re-declaring t
after clearing the setTimeout
. 您需要阻止执行其余代码,实际上您在清除setTimeout
后重新声明了t
。 Fiddle 小提琴
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);
}
Or just use the else
statement: 或者只使用else
语句:
if (c == 5) {
clearTimeout(t);
// do something else
}else{
t = setTimeout(timedCount, 1000);
}
There will never be a timeout to clear when you call clearTimeout
as the last one will have already fired and the next one won't have been set yet. 当你调用clearTimeout
时,永远不会有超时清除,因为最后一个已经被触发,而下一个尚未设置。
You want to change your logic so that if (c !== 5) { setTimeout(etc etc) }
你想改变你的逻辑,以便if (c !== 5) { setTimeout(etc etc) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.