I wrote a timer object that works like a stop watch (click once and the timer starts, click again and it stops, double click and it resets). Everything works fine if I only activate one timer. When I activate a second timer, the first one stops working. When I activate a third timer, the second stops working.
I dynamically created each timer object to give each timer it's own name (window[timer1]). But they are not acting independently. What am I missing to make the timer objects operate independently of each other?
function Clock() {
this.element = "";
this.minute = 0;
this.toggle = true;
this.active = false;
this.startClock = startClock;
this.stopClock = stopClock;
function startClock() {
minute = this.minute;
element = this.element;
minute = checkTime(minute);
document.getElementById(element).innerHTML = minute;
minute++;
this.minute = minute;
t=setTimeout(function(){startClock()},1000);
this.counter = t;
}
function checkTime(i) {
if (i<10)
{
i="0" + i;
}
return i;
}
function stopClock() {
document.getElementById(element).innerHTML = this.minute;
clearTimeout(t);
}
}
function initClock(ele) {
value = document.getElementById(ele).innerHTML;
if (typeof window[ele] == 'undefined') {
window[ele] = new Clock();
window[ele].element = ele;
}
if (value == "start" || window[ele].active == false) {
window[ele].toggle = true;
} else {window[ele].toggle = false;}
if (window[ele].toggle) {
window[ele].toggle = false;
window[ele].active = true;
if (value == "start") {
window[ele].minute = 0;
}
window[ele].startClock();
}
else {
window[ele].toggle = true;
window[ele].active = false;
window[ele].stopClock();
}
}
function clearClock(ele) {
document.getElementById(ele).innerHTML= "start";
this.element = "";
this.minute;
this.toggle;
this.counter;
}
This will run two separate instances of second timers from 0- well, forever. Just modify it to what you need.
etc...
Doing it in reverse count down just set your
c1
,c2
vars to = and changec1=c1+1
toc1=c1-1
andc2=c2+1
toc2=c2-1
.Reviving an old post (don't flame me please)...
I reworked and offer a complete solution, with formatting & milliseconds.
Kudos goes to:
I went generic with window.onload - JQuery users be sure to use .ready( ) API handler.
I minified] (jscompress.com) the code for simplicity - use jsbeautifier.org to 'unminify'.
Great tool for AJAX time studies / AJAX stopwatch
Warning! Bringing the timeout to "1" will increase CPU significantly. I found a happy median around 35-80 ms.
Try it now! - This works with modern browsers supporting ECMAScript 5
Try it now! - This works with older browsers using JQuery proxy in lieu of bind
You have some scope issues. E.g.
This will declare
minute
,element
andt
in global scope, thus every call tostartClock
will overwrite these values.Here is an refactored version:
Read more about Objects in JavaScript.