我目前正在用启动和停止按钮用Javascript制作番茄定时器。在使用clearInterval()停止倒计时后,使用setInterval()开始倒数时遇到了问题。我有2个在单击按钮时调用的函数,一个函数使用setInterval()启动倒数计时,另一个函数使用clearInterval()停止计时。我不确定发生了什么,这是我在下面的实现:

var startTime = 25; // this value will change depending on what the user selects, default value is 25:00
var time = startTime * 60; //number of seconds total
var intervalID; //used for setInterval()

var pomodoroTimer = document.getElementById('pomodoro-timer');


function updateTimer(){
    let minutes = Math.floor(time/60);
    let seconds = time % 60;

    minutes = minutes < 10 ? '0' + minutes : minutes;
    seconds = seconds < 10 ? '0' + seconds : seconds;

    pomodoroTimer.innerHTML = minutes + ':'+ seconds;
    time--;
}

function startTimer(){
    if(!intervalID){ // to prevent multiple setIntervals being queued up
        updateTimer(); // call this once to stop clock from taking too long on first use of the setInterval function
        intervalID = setInterval(updateTimer, 1000);
    }
}

function stopTimer(){
    clearInterval(intervalID);
}

最佳答案

function stopTimer(){
    clearInterval(intervalID);
    intervalID = undefined;
}

关于javascript - setInterval()在clearInterval()之后不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60863275/

10-13 06:52