setInterval() 在 clearInterval() 后不起作用

雷H99

我目前正在用 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;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章