Search code examples
javascriptjquerycountdown

Countdown HH:MM:SS in Jquery


I want to countdown timer in format of hh:mm:ss so I use this code it's convert seconds into required format but when I count down it display me NaN. Can you tell me what I am doing wrong Here is code

<div id="timer"></div>

JS

String.prototype.toHHMMSS = function () {
    var sec_num = parseInt(this, 10); // don't forget the second parm
    var hours = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);

    if (hours < 10) {
        hours = "0" + hours;
    }
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    if (seconds < 10) {
        seconds = "0" + seconds;
    }
    var time = hours + ':' + minutes + ':' + seconds;
    return time;
}

var count = '62';
count = count.toHHMMSS();

var counter = setInterval(timer, 1000);

function timer() {

    count--;
    if (count <= 0) {
        clearInterval(counter);
        return;
    }

    $('#timer').html(count);
}

Here is JsFiddle link CountDown Timer


Solution

  • Well, let's take a look at what your code does:

    • Set count to the string value 62.
    • Convert it to HHMMSS, so now count is equal to the string 00:01:02
    • Start the timer.
    • On the first run of the timer, decrement count. Erm... count is a string, you can't decrement it. The result is not a number.

    Okay, so with that out of the, way how about fixing it:

    function formatTime(seconds) {
        var h = Math.floor(seconds / 3600),
            m = Math.floor(seconds / 60) % 60,
            s = seconds % 60;
        if (h < 10) h = "0" + h;
        if (m < 10) m = "0" + m;
        if (s < 10) s = "0" + s;
        return h + ":" + m + ":" + s;
    }
    var count = 62;
    var counter = setInterval(timer, 1000);
    
    function timer() {
        count--;
        if (count < 0) return clearInterval(counter);
        document.getElementById('timer').innerHTML = formatTime(count);
    }