Jeff Burghess Jeff Burghess - 5 months ago 18
Javascript Question

Call a function when my timer reaches zero

I've got a timer function as follows (which I've just grabbed off a jsfiddle):

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

function returnDate(){
return Number(new Date);
}

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

function updateTimer()
{
msLeft = endTime - (returnDate());
if ( msLeft < 1000 ) {
element.innerHTML = "0:00";
} 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 call the function and set it to countdown to 2 minutes like so:

$(".btn-start").click(function(){
countdown("countdown-2-minutes",2,0);

});


I have another element with id
countdown-8-minutes
that I want to start immediately when the timer on
countdown-2-minutes
reaches 0. How should I do this? I suppose an okay way would be to monitor when the html on the first element reads "0:00" but I don't exactly know how to implement that.

Answer

Here's what I would suggest; First change your countdown() function to accept a callback parameter:

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

    function returnDate(){
    return Number(new Date);
    }

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

    function updateTimer()
    {
        msLeft = endTime - (returnDate());
        if ( msLeft < 1000 ) {
            element.innerHTML = "0:00";
            if (typeof callback === 'function') {
                callback.call()
            }
        } 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();
}

then pass that callback with your initial call:

$(".btn-start").click(function(){
    countdown("countdown-2-minutes",2,0, function(){countdown("countdown-8-minutes",8,0);});
});