一页上有多个倒数计时器 [英] Multiple countdown timers on one page

查看:68
本文介绍了一页上有多个倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

有没有人可以轻松更改此脚本?正常工作的两个计时器?

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>


推荐答案

您正在做的一些事情会阻止您扩展代码。如果您想要一个可重复使用的计时器,则无法硬设置它将使用的变量。因此,第一件事就是摆脱顶部的三个变量,并在函数范围内重新创建它们。

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).

然后,您将计时器变量用作点击处理程序和setInterval的参数,但从未使用过。该变量将被设置为事件处理程序上的click事件(再次未使用),并且在setInterval上未定义。因此,他们确实不应该在那里。

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.

性能问题,您可能想知道的是,您每秒钟都要对DOM进行一次DOM查找。

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.

到那时,您的函数看起来或多或少像这样

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" />

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

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

-- 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.

这篇关于一页上有多个倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆