javascript/jquery countdown timer with JSfiddle example?

前端 未结 4 1423
后悔当初
后悔当初 2021-01-21 02:50

I am building a few things and one of them is a countdown timer, the countdown will never be over an hour so all I need to do is countdown minutes and seconds.

I have it

4条回答
  •  死守一世寂寞
    2021-01-21 03:32

    I understand that an answer has already being accepted but would like to throw in my 2c: I like to avoid extra coding whenever possible. Using Jonathan Lonowski's approach, I would improve it like:

    var interval = setInterval(function() {
        var timer = $('span').html().split(':');
        //by parsing integer, I avoid all extra string processing
        var minutes = parseInt(timer[0],10);
        var seconds = parseInt(timer[1],10);
        --seconds;
        minutes = (seconds < 0) ? --minutes : minutes;
        if (minutes < 0) clearInterval(interval);
        seconds = (seconds < 0) ? 59 : seconds;
        seconds = (seconds < 10) ? '0' + seconds : seconds;
        minutes = (minutes < 10) ?  '0' + minutes : minutes;
        $('span').html(minutes + ':' + seconds);
    }, 1000);
    

提交回复
热议问题