javascript 一页上有多个倒数计时器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22796620/
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-27 23:47:36  来源:igfitidea点击:

Multiple countdown timers on one page

javascripttimercountdown

提问by user3486844

Currently working on a project that requires two timers on one page. The timers need to have a start button and both have different timings (i.e. timer1 lasts 10 secs and timer2 lasts 20). Here's the script I'm using, but I don't know how to duplicate the timer and let each timer work independently.

目前正在处理一个需要在一页上设置两个计时器的项目。计时器需要有一个开始按钮,并且两者都有不同的计时(即 timer1 持续 10 秒,timer2 持续 20 秒)。这是我正在使用的脚本,但我不知道如何复制计时器并让每个计时器独立工作。

Is there anyone who can easily change this script to a functioning one for two timers?

有没有人可以轻松地将此脚本更改为两个计时器的功能?

<html>
<head>
<script language="JavaScript" type="text/javascript">
    var interval;
    var minutes = 0;
    var seconds = 10;

    function countdown(element) {
        interval = setInterval(function(timer) {
            var el = document.getElementById(element);
            if(seconds == 0) {
                if(minutes == 0) {
                    (el.innerHTML = "STOP!");     

                    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 ? '' : '';
            el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + '';
            seconds--;
        }, 1000);
    }
var start = document.getElementById('start');

start.onclick = function(timer) {
    if (!interval) {
        countdown('countdown');
    }
}

</script>
</head>

<body>
<div id='countdown'></div>
<input type="button" onclick="countdown('countdown');this.disabled = true;" value="Start" />
</body>
</html>

回答by guioconnor

There are few things you're doing that prevent you from expanding the code. If you want a reusable timer, you can't hard set the variables it will use. So first thing is to get rid of the three variables at the top and recreate them WITHIN the scope of the function.

您正在做的事情很少会阻止您扩展代码。如果您想要一个可重复使用的计时器,则不能硬设置它将使用的变量。所以第一件事是去掉顶部的三个变量,并在函数的作用域内重新创建它们。

That way, every time the function is called, a new set of variables is created for its execution.

这样,每次调用该函数时,都会为其执行创建一组新变量。

The minutes and seconds are probably best passed as parameters and interval should be defined within the scope of function.

分钟和秒可能最好作为参数传递,间隔应该在函数范围内定义。

Secondly you are setting the click handler BOTH inline and within the script. Get rid of one of them (preferably get rid of the inline version).

其次,您正在内联和脚本内设置点击处理程序。摆脱其中之一(最好摆脱内联版本)。

Then, you have a timer variable as a parameter for the click handler and setInterval but never used. That variable will be set to the click event on the event handler (and again, is not being used) and will be undefined on setInterval. So they really shouldn't be there.

然后,您有一个计时器变量作为点击处理程序和 setInterval 的参数,但从未使用过。该变量将设置为事件处理程序上的点击事件(同样,未使用)并且在 setInterval 上未定义。所以他们真的不应该在那里。

A performance issue, you may want to know about is that you are doing a DOM lookup for the counters EVERY second. You should get it once per function call at the beginning and cache it.

您可能想知道的一个性能问题是您每秒钟都在为计数器进行 DOM 查找。您应该在开始时为每个函数调用获取一次并缓存它。

At that point, you function would look more or less like this

在这一点上,你的函数看起来或多或少是这样的

function countdown(element, minutes, seconds) {
    // Fetch the display element
    var el = document.getElementById(element);

    // Set the timer
    var interval = setInterval(function() {
        if(seconds == 0) {
            if(minutes == 0) {
                (el.innerHTML = "STOP!");     

                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 ? '' : '';
        el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + '';
        seconds--;
    }, 1000);
}

And your setup more or less like this

你的设置或多或少是这样的

//Start as many timers as you want

var start1 = document.getElementById('timer1');
var start2 = document.getElementById('timer2');

start1.onclick = function() {
    countdown('countdown1', 0, 15);
}

start2.onclick = function() {
    countdown('countdown2', 0, 10);
}

Of course, you need the extra button and counter

当然,你需要额外的按钮和计数器

<div id='countdown1'></div>
<div id='countdown2'></div>
<input id="timer1" type="button" value="Start timer 1" />
<input id="timer2" type="button" value="Start timer 2" />

Working example: http://codepen.io/anon/pen/Jmpcq/?editors=101

工作示例:http: //codepen.io/anon/pen/Jmpcq/?editors=101

-- Note: for precise timers, setInterval()may not be a good option because the precise interval is not guaranteed and time tracked by it may be delayed after a while. For applications where precise time is critical, there are other methods (e.g. https://sitepoint.com/creating-accurate-timers-in-javascript& https://html5rocks.com/en/tutorials/webperformance/usertimin), thanks @KaiKarver for pointing out in the comments.

-- 注意:对于精确的定时器,setInterval()可能不是一个好的选择,因为精确的间隔不能保证,它跟踪的时间可能会延迟一段时间。对于精确时间至关重要的应用程序,还有其他方法(例如https://sitepoint.com/creating-accurate-timers-in-javascript& https://html5rocks.com/en/tutorials/webperformance/usertimin),谢谢@KaiKarver 在评论中指出。

回答by dannyde

var interval;

var countdown1 = {
    minutes:0,
    seconds: 10
};

var countdown2 = {
    minutes:0,
    seconds: 2
}

function countdown(element) {
    alert(element);
    var cd;
    element === 'countdown1' ? cd = countdown1 : cd = countdown2;
    interval = setInterval(function(timer) {
        var el = document.getElementById(element);
        if(cd.seconds == 0) {
            if(cd.minutes == 0) {
                (el.innerHTML = "STOP!");     

                clearInterval(interval);
                return;
            } else {
                cd.minutes--;
                cd.seconds = 60;
            }
        }
        if(cd.minutes > 0) {
            var minute_text = cd.minutes + (cd.minutes > 1 ? ' minutes' : ' minute');
        } else {
            var minute_text = '';
        }
        var second_text = seconds > 1 ? '' : '';
        el.innerHTML = minute_text + ' ' + cd.seconds + ' ' + second_text + '';
        cd.seconds--;
    }, 1000);
}
var start = document.getElementById('start');


 <div id='countdown'></div>
 <input type="button" onclick="countdown('countdown1');this.disabled = true;" value="Start" />
 <div id="countdown1"></div>

 <input type="button" onclick="countdown('countdown2');this.disabled = true;" value="Start" />
 <div id="countdown2"></div>

fiddle: http://jsfiddle.net/dn3hJ/

小提琴:http: //jsfiddle.net/dn3hJ/