javascript - setTimeout() 方法中的 clearTimeout() 在 JS 中不起作用

标签 javascript timer settimeout

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);
}

jsFiddle

最佳答案

您需要阻止执行其余代码,实际上您是在清除setTimeout 后重新声明tFiddle

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/

相关文章:

javascript - 如何调试严重崩溃的 javascript 应用程序?

Javascript - .split 与正则表达式返回所有匹配项(如果下一个字符不是)

Python Timer 使解释器崩溃

Javascript - 对象属性设置的重复

javascript - 带日期的 Highcharts 气泡图?

c++ - 有没有好的轻量级多平台C++定时器队列?

c - 如何编译 POSIX 定时器

javascript - setTimer 不适用于 Jquery 悬停

javascript - setTimeout 有或没有匿名函数?有什么不同?

node.js - 在 Node.js 中设置计时器