清除倒数计时器 [英] Clear countdown timer

查看:78
本文介绍了清除倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this function that implements a countdown (MM:SS). I pass the minutes and seconds in the function and the countdown will start. Now, I'd like the countdown to reset and restart everytime I pass new values in. Currently what happens is that if I call the countdown function multiple times then I will have multiple timers running together while instead I need to reset and restart the same timer everytime I pass in new minutes and seconds. Thanks

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();
    }

推荐答案

获取当前计时器的ID,并在设置新计时器之前将其取消.

Retrieve the id of the current timer and cancel it before setting the new one.

w3schools提供的礼貌:-

Courtesy w3schools: -

var myVar;

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

function myStopFunction() {
    clearTimeout(myVar);

}

这篇关于清除倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆