Search code examples
javascriptcountdown

javascript countdown stutter


I have a countdown like this one:

var countdown = {
    startInterval: function() {
        var count = 600
        var countorig = 600;
        var currentId = setInterval(function() {
            var min = (count - (count % 60)) / 60;
            var sec = count % 60;
            if (sec < 10) {
                $('#timer').html(min + ':0' + sec);
            } else {
                $('#timer').html(min + ':' + sec);
            }
            $('#time').val(countorig - count);
            if (count == 0) {
                $('#form').submit();
            }--count;
        }, 1000);
        countdown.intervalId = currentId;
    }
};

It works. But if I load the page, the countdown starts but it stutter it is not "round" like a clock is.

JSFiddle.


Solution

  • setInterval isn’t exact. You should use Dates instead, to get an accurate time, and then choose an interval of less than one second to get a smoother clock. Here’s a demo!

    var countdown = {
        startInterval: function() {
            var count = 600;
            var start = new Date(); // The current date!
    
            var currentId = setInterval(function() {
                var difference = Math.max(0, count - (new Date() - start) / 1000 | 0);
                var min = difference / 60 | 0;
                var sec = difference % 60;
    
                $('#timer').text(min + ':' + (sec < 10 ? '0' : '') + sec);
                $('#time').val(difference);
    
                if(count === 0) {
                    $('#form').submit();
                }
            }, 200);
    
            countdown.intervalId = currentId;
        }
    };