clearTimeout()里面的setTimeout()方法在JS中不起作用

Kat*_*ram 6 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);
}
Run Code Online (Sandbox Code Playgroud)

的jsfiddle

Pie*_*rre 8

您需要阻止执行其余代码,实际上您t在清除后重新声明setTimeout.小提琴

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);
}
Run Code Online (Sandbox Code Playgroud)

或者只使用else声明:

if (c == 5) {
  clearTimeout(t);
  // do something else
}else{
  t = setTimeout(timedCount, 1000);
}
Run Code Online (Sandbox Code Playgroud)