javascript countdown clock

前端 未结 4 628
执念已碎
执念已碎 2021-01-03 19:05
 

        
4条回答
  •  执念已碎
    2021-01-03 19:36

    The answers I see here work pretty well but are not entirely rigorous. Although setInterval() seems like the right function to use, it suffers from a slight "drift" over time. Also, if some other JavaScript function takes a second or more to execute then your countdown clock can get stalled and show the wrong time.

    Although these occurrences might be unlikely, greater precision is really not more difficult. What you want is a timer that pulls the clock back from any inaccuracy. You'll need to calculate time off the system clock rather than from the frequency of time intervals, and for this you'll have to give up setInterval() in favor of a series of setTimeout() calls. The following code shows how.

    function countdown( elementName, minutes, seconds )
    {
        var element, endTime, hours, mins, msLeft, time;
    
        function twoDigits( n )
        {
            return (n <= 9 ? "0" + n : n);
        }
    
        function updateTimer()
        {
            msLeft = endTime - (+new Date);
            if ( msLeft < 1000 ) {
                element.innerHTML = "countdown's over!";
            } 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();
    }
    

    Try it: http://jsfiddle.net/mrwilk/qVuHW

    If your clock should by chance align very closely to the seconds of the system clock, your countdown timer can appear to "miss beats" due to receiving timeout events just slightly before or just slightly after a one-second interval. The solution is to align your events on the half-second; that is, midway between the beats of the seconds of the system clock. That what the 500's in the code do, where 500ms = ½sec.

    The only other matter worth noting is that the code here displays hours as well as minutes and seconds; that is, HH:MM:SS. Computing hours, minutes and seconds from milliseconds is not difficult but is a bit awkward, and it's simplest to let the Date object do this work for you.

提交回复
热议问题