javascript 倒计时时钟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4584397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:12:39  来源:igfitidea点击:

javascript countdown clock

javascriptclock

提问by roi

 <script>
var interval;
var minutes = 1;
var seconds = 5;
window.onload = function() {
    countdown('countdown');
}

function countdown(element) {
    interval = setInterval(function() {
        var el = document.getElementById(element);
        if(seconds == 0) {
            if(minutes == 0) {
                el.innerHTML = "countdown's over!";                    
                clearInterval(interval);
                return;
            } else {
                minutes--;
                seconds = 60;
            }
        }
        if(minutes > 0) {
            var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
        } else {
            var minute_text = '';
        }
        var second_text = seconds > 1 ? 'seconds' : 'second';
        el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + ' remaining';
        seconds--;
    }, 1000);
}
</script>

this is a good countdown clock and i want to show the time in datalist how do i do it? like in this site www.1buy1.co.il

这是一个很好的倒计时时钟,我想在数据列表中显示时间我该怎么做?就像在这个网站 www.1buy1.co.il

回答by Dragonfly

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() 似乎是使用正确的函数,但随着时间的推移它会出现轻微的“漂移”。此外,如果其他 JavaScript 函数需要一秒钟或更长时间才能执行,那么您的倒计时时钟可能会停止并显示错误的时间。

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.

尽管这些情况不太可能发生,但更高的精度实际上并不困难。您想要的是一个可以将时钟从任何不准确情况中拉回来的计时器。您需要根据系统时钟计算时间,而不是根据时间间隔的频率,为此您必须放弃 setInterval() 以支持一系列 setTimeout() 调用。下面的代码展示了如何。

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

试试看: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.

如果您的时钟碰巧与系统时钟的秒数非常接近,您的倒数计时器可能会出现“错过节拍”,因为在一秒间隔之前或之后接收超时事件。解决方案是在半秒内对齐您的事件;也就是说,在系统时钟的秒拍之间。这就是代码中 500 的作用,其中 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.

唯一值得注意的是这里的代码显示小时以及分钟和秒;即,HH:MM:SS。从毫秒计算小时、分钟和秒并不困难,但有点笨拙,最简单的是让 Date 对象为您完成这项工作。

回答by Raynos

I've cleaned up the above code and made it format like your example. It also removed the global variables and allows you to create multiple timers.

我已经清理了上面的代码并使它的格式像你的例子一样。它还删除了全局变量并允许您创建多个计时器。

There's a live link here http://jsfiddle.net/Apnu2/6/

这里有一个实时链接http://jsfiddle.net/Apnu2/6/

countdown('countdown', 1, 5);
function countdown(element, minutes, seconds) {
    // set time for the particular countdown
    var time = minutes*60 + seconds;
    var interval = setInterval(function() {
        var el = document.getElementById(element);
        // if the time is 0 then end the counter
        if(time == 0) {
            el.innerHTML = "countdown's over!";    
            clearInterval(interval);
            return;
        }
        var minutes = Math.floor( time / 60 );
        if (minutes < 10) minutes = "0" + minutes;
        var seconds = time % 60;
        if (seconds < 10) seconds = "0" + seconds; 
        var text = minutes + ':' + seconds;
        el.innerHTML = text;
        time--;
    }, 1000);
}

回答by anand j

                            <script>
            var s=3600;
            var h=Math.floor(s/3600);
            var m=Math.floor((s%3600)/60);
            var sec=(s%60);
            window.clearInterval(x);
            function clock()
            {
             if(m!=0)
             if(sec==0){
             m=m-1; sec=59;} 
             if(h!=0)
             if(m==0){
             h=h-1;m=59;
             sec=59;}
             if((m==0&&h==0&&sec==0))
             $(this).stop();
             --sec;
             var hr=(h<10? "0":"")+h;
             var minu=(m<10? "0":"")+m;
             var second=(sec<10? "0":"")+sec;
             document.getElementById("time").innerHTML=hr+":"+ minu +":"+second ;
            }
            var x=window.setInterval(clock,10);

            </script>

回答by mplungjan

The elementin the script is the id of the tag you pass to the function.
So countdown('div1')will show a timer in a tag with id="div1"

element脚本是你传递给函数的标签的ID。
所以countdown('div1')将在 id="div1" 的标签中显示一个计时器

However your particular timer does not allow multiple instances and uses a global var called interval.

但是,您的特定计时器不允许多个实例并使用称为间隔的全局变量。

Generate the JSON on the server and the rest takes care of itself

在服务器上生成 JSON,其余的自己处理

HERE is an OO version that is more precise since it is only calculating the end time instead of relying on interval which will block if the browser is busy: http://jsbin.com/ujuzo5/edit

这是一个更精确的 OO 版本,因为它只计算结束时间而不是依赖于浏览器繁忙时会阻塞的时间间隔:http: //jsbin.com/ujuzo5/edit

And here is my original solution with the help of the good folks at SO here: Broken closure - please help me fix it

这是我在 SO 的好人的帮助下的原始解决方案:Broken closure - please help me fix it

<script type="text/javascript">
// generate this on the server and note there is no comma after the last item
var counters = {
  "shoes":{"id":"shoe1","minutes":1,"seconds":5},
  "trousers":{"id":"trouser1","minutes":10,"seconds":0}
};

var intervals = {};

window.onload = function() {
  for (var el in counters) { countdown(counters[el]) };
}
function countdown(element) {
    var minutes = element.minutes;
    var seconds = element.seconds;

    intervals[element.id] = setInterval(function() {
        var el = document.getElementById(element.id);
        if(seconds == 0) {
            if(minutes == 0) {
                el.innerHTML = "countdown's over!";                    
                clearInterval(intervals[element.id]);
                return;
            } else {
                minutes--;
                seconds = 60;
            }
        }
        if(minutes > 0) {
            var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
        } else {
            var minute_text = '';
        }
        var second_text = seconds > 1 ? 'seconds' : 'second';
        el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + ' remaining';
        seconds--;
        // optionally update the member values
        element.minutes=minutes;
        element.seconds=seconds;
    }, 1000);
}

</script>
shoes: <span id="shoe1"></span><br />
trousers: <span id="trouser1"></span><br />