清除倒数计时器

时间:2018-01-29 01:11:32

标签: javascript timer countdown

我有这个实现倒计时(MM:SS)的功能。我在函数中传递分钟和秒钟,倒计时将开始。现在,我希望每次传递新值时都会重置并重新启动倒计时。目前发生的情况是,如果我多次调用倒计时功能,那么我将同时运行多个计时器,而我需要重置并重新启动每当我通过新的分钟和秒钟时,计时器。感谢

function countdown(minutes, seconds)
    {
        var endTime, hours, mins, msLeft, time;

        function twoDigits( n )
        {
            return (n <= 9 ? "0" + n : n);
        }

        function updateTimer()
        {
            canvas.style.color = "black";
            canvas.innerHTML = "00:00"; //clear canvas
            msLeft = endTime - (+new Date);
            if ( msLeft < 1000 )                
                flashyText();
            else {
                canvas.style.color = "white";
                time = new Date( msLeft );
                hours = time.getUTCHours();
                mins = time.getUTCMinutes();
                canvas.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds());
                setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
            }
        }

        endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
        updateTimer();
    }

1 个答案:

答案 0 :(得分:1)

检索当前计时器的ID并在设置新计时器之前将其取消。

礼貌w3schools: -

var myVar;

function myFunction() {
    myVar = setTimeout(function(){ alert("Hello") }, 3000);
}

function myStopFunction() {
    clearTimeout(myVar);

}