Search code examples
javascripttimercountdown

Javascript countdown timer gets stuck after 1 sec


I need to create a javascript countdown timer, I've been trying to do it using setInterval method but when I pass the seconds as a parameter it keeps looping so that it only goes down by 1 second then stops. Here is my code:

JavaScript :

var second = 120;
document.getElementById('timer').innerHTML = second;
function setTimer(second)
{
    second--;
    document.getElementById('timer').innerHTML = second;
    return second;
}
second = window.setInterval(setTimer, 1000, second); //Timer for user display

Thanks!


Solution

  • var second = 120;
    var timeOutFunction;
    document.getElementById('timer').innerHTML = second;
    function setTimer()
    {
        second--;
        document.getElementById('timer').innerHTML = second;
        if(second == 0)
            clearInterval(timeOutFunction);
    }
    timeOutFunction = setInterval(setTimer, 1000); //Timer for user display
    

    http://jsfiddle.net/Jd4tx/