我怎样才能让我的计数器停在 0?它递减为负数

How can I get my counter to stop at 0? It decrements to negative numbers

我的代码有什么问题?我无法让计时器停在 0。它一直下降到负数。我设置了 clearInterval,为什么计时器不停止?

var seconds = 30;

$("#timer").on("click", run);

$("#timer").on("click", show);

var timer;

function run() {

    clearInterval(timer);
    timer = setInterval(decrement, 1000);

}

function decrement() {

    seconds--;
    $("#timer").html("<h2>" +"Time Remaining: " + seconds + "</h2>");

}

// Stop function

function stop() {

    clearInterval(timer);

}

// When seconds hit zero

if (seconds === 0) {

    stop();
    alert("Time's Up!");

}

你的问题是你的 if 语句是 运行 一次,但它不会再检查一次,然后再也不会 运行 了。如果将 if 语句移动到递减函数中,您应该会非常好。

该函数可能类似于,

function decrement() {
    seconds--;    
    if (seconds === 0) {
        stop();
        alert("Time's Up!");
    }
    $("#timer").html("<h2>" +"Time Remaining: " + seconds + "</h2>");
}