Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

javascript - Multiple countdown timers on one page

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

Working example: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...