Search code examples
javascriptsetintervalcountdown

disable countdown on javascript


I have a javascript code which can give an error when countdown ends. I need to create a code to stop countdown. It can start countdown but I can't stop it. Here is my code:

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

I can start countdown from 5 minutes with this option:

countdown( "countdown", 5, 00 );

Solution

  • Use clearTimeout on your setTimeout by assigning the setTimeout to a variable, in this case 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);
    }