首页 > 解决方案 > 倒数到零并停在零

问题描述

我从一分钟开始倒计时,希望它停在零。我不确定我的逻辑是否正确,因为这个数字超过了 0 变成了负数。

我试过清除间隔(clearInterval(interval)),但它似乎不起作用。

var timer = [0,0,0]; //seconds,hundredths,thousandths
var counter = 10; //starts at 60s; 10s for testing purposes
var interval;
var timerRunning = false;

//countdown timer
function runTimer() {
    let currentTime = leadingZero(timer[0]) + ":" + leadingZero(timer[1]);
    theTimer.innerHTML = currentTime;

    timer[2]--; //counting down in thousandths increments

    timer[0] = (counter + Math.floor(timer[2]/100)); //" second increments
    timer[1] = Math.floor(timer[2] - (Math.floor(timer[2]/100) * 100)); //" hundredth increments

    if (timer == [0,0,0]) { 
      clearInterval(interval);
      timer = [0,0,0];
      timerRunning = false;

      theTimer.innerHTML = "00:00";
    }
}

// Start the timer:
function start() {
    let textEnterdLength = testArea.value.length;
    if (textEnterdLength === 0 && !timerRunning) {
        timerRunning = true;
        interval = setInterval(runTimer, 10);
    }
    //console.log(textEnterdLength);
}

我希望输出停止在“00:00”,但它会通过它并变成负数。

标签: javascriptsetintervalclearinterval

解决方案


推荐阅读