在 javascript 上禁用倒计时

disable countdown on javascript

我有一个 javascript 代码可以在倒计时结束时给出错误。我需要创建一个代码来停止倒计时。它可以开始倒计时,但我无法停止。 这是我的代码:

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

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

    function updateTimer()
    {
        msLeft = endTime - (+new Date);
        if ( msLeft < 1000 ) {
            givestrongerror(error_timeout);
        } else {
            time = new Date( msLeft );
            hours = time.getUTCHours();
            mins = time.getUTCMinutes();
            element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() );
            setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
        }
    }

    element = document.getElementById( elementName );
    endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
    updateTimer();
}

我可以使用此选项从 5 分钟开始倒计时:

countdown( "countdown", 5, 00 );

您有一个选择是简单地清除超时。 setTimeout() returns 一个超时 ID,可用于通过 clearTimeout() 清除它。

var countdown_timeout_id;

function startCountdown()
{
  countdown_timeout_id = window.setTimeout(function() { /*blah*/ }, 100);
}

function stopCountdown()
{
  window.clearTimeout(countdown_timeout_id);
}

如果您想让用户停止倒计时功能,您可以 return 具有 stopCountdown 功能的对象。

return {
  stop: stopCountdown
}   

通过将 setTimeout 分配给变量,在您的 setTimeout 上使用 clearTimeout,在本例中为 timeout.

//make timeout global
var timeout = null;
function countdown( elementName, minutes, seconds )
{
var element, endTime, hours, mins, msLeft, time;

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

function updateTimer()
{
    msLeft = endTime - (+new Date);
    if ( msLeft < 1000 ) {
        givestrongerror(error_timeout);
    } else {
        time = new Date( msLeft );
        hours = time.getUTCHours();
        mins = time.getUTCMinutes();
        element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() );

        //set variable 'timeout' to the setTimeout that could be erroneous
        timeout = setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );

    }
}

element = document.getElementById( elementName );
endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
updateTimer();
}

//call this function to end the timeout
function endTimeout(){
    clearTimeout(timeout);
}