且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

javascript倒计时时钟

更新时间:2023-02-26 17:07:53

我在这里看到的答案效果很好,但是不完全严谨。虽然setInterval()看起来像是正确使用的功能,但随着时间的推移它会有轻微的漂移。此外,如果其他一些JavaScript函数需要一秒或更长时间来执行,那么倒计时时钟可能会停止并显示错误的时间。

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.

虽然这些事件可能不太可能发生,但更大精确度确实不难。你想要的是一个计时器,可以将时钟从任何不准确状态中拉回来。您需要计算系统时钟的时间而不是时间间隔的频率,为此您必须放弃setInterval()以支持一系列setTimeout()调用。以下代码显示了如何。

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();
}

试一试: http://jsfiddle.net/mrwilk/qVuHW

如果您的时钟应该与系统的秒数非常接近地对齐时钟,您的倒数计时器可能会出现错过节拍,因为在一秒间隔之前或之后稍微接收超时事件。解决方案是在半秒内调整您的事件;也就是说,在系统时钟的秒数之间的中途。这就是代码中500的含义,其中500ms =½sec。

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.

另外值得注意的另一个问题是这里的代码显示小时数以及分钟数和秒数。也就是说,HH:MM:SS。从毫秒开始计算小时,分钟和秒并不困难,但有点尴尬,让Date对象为你工作最简单。

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.