clearTimeout()
inside setTimeout()
方法在 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
。 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);
}
或者只使用else
语句:
if (c == 5) {
clearTimeout(t);
// do something else
}else{
t = setTimeout(timedCount, 1000);
}
关于javascript - setTimeout() 方法中的 clearTimeout() 在 JS 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15438532/