如何在一个页面上创建多个独立运行的计时器——javascript?
我编写了一个计时器对象,它的工作原理类似于秒表(单击一次计时器启动,再次单击计时器停止,双击计时器重置)。如果我只激活一个计时器,一切正常。当我启动第二个计时器时,第一个计时器停止工作。当我启动第三个计时器时,第二个计时器停止工作 我动态创建了每个timer对象,为每个timer指定自己的名称(window[timer1])。但它们并非独立行动。要使计时器对象彼此独立运行,我缺少了什么如何在一个页面上创建多个独立运行的计时器——javascript?,javascript,oop,Javascript,Oop,我编写了一个计时器对象,它的工作原理类似于秒表(单击一次计时器启动,再次单击计时器停止,双击计时器重置)。如果我只激活一个计时器,一切正常。当我启动第二个计时器时,第一个计时器停止工作。当我启动第三个计时器时,第二个计时器停止工作 我动态创建了每个timer对象,为每个timer指定自己的名称(window[timer1])。但它们并非独立行动。要使计时器对象彼此独立运行,我缺少了什么 function Clock() { this.element = ""; this.minute =
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.element=“”;
这1.5分钟=0;
this.toggle=true;
this.active=false;
this.startClock=startClock;
this.stopClock=stopClock;
函数startClock(){
分钟=this.minute;
element=this.element;
分钟=检查时间(分钟);
document.getElementById(element).innerHTML=minute;
分钟++;
this.minute=分钟;
t=setTimeout(函数(){startClock()},1000);
this.counter=t;
}
功能检查时间(i){
如果(i你有一些范围问题
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;
}
这将在全局范围内声明minute
、element
和t
,因此对startClock
的每次调用都将覆盖这些值
以下是重构版本:
function Clock(element) {
this.element = element;
this.minute = 0;
this.toggle = true;
this.active = false;
}
Clock.prototype = {
startClock: function() {
this.minute = this.checkTime(this.minute);
this.element.innerHTML = this.minute;
this.minute++;
var that = this;
this.counter = setTimeout(function(){that.startClock()},1000);
},
checkTime = function(i) {
if (i<10) {
i="0" + i;
}
return i;
},
stopClock: function() {
this.element.innerHTML = this.minute;
clearTimeout(this.counter);
},
clearClock: function() {
this.element.innerHTML= "start";
this.element = "";
this.minute = 0;
this.toggle = true;
this.counter = null;
}
}
function initClock(ele) {
value = document.getElementById(ele).innerHTML;
if (typeof window[ele] == 'undefined') {
window[ele] = new Clock(document.getElementById(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();
}
}
功能时钟(元件){
this.element=元素;
这1.5分钟=0;
this.toggle=true;
this.active=false;
}
Clock.prototype={
startClock:function(){
this.minute=this.checkTime(this.minute);
this.element.innerHTML=this.minute;
这个.minute++;
var=这个;
this.counter=setTimeout(函数(){that.startClock()},1000);
},
检查时间=功能(i){
如果(i这将从0运行两个独立的第二个计时器实例-好的,永远。
只需根据需要修改即可
等等
反向倒计时只需将您的c1
,c2
变量设置为=并将c1=c1+1
更改为c1=c1-1
和c2=c2+1
更改为c2=c2-1恢复旧帖子(请不要解雇我)
我重新设计并提供了一个完整的解决方案,包括格式和毫秒
荣誉归于:
- Felix Kling和OP用于原始代码和线程
- Ildar Shaimordanov表示“[document.insertAfter]”(用于DOM'laps')code.google.com/p/jsxt/source/browse/trunk/js/web/document.insertAfter.js?r=220
- 创建phpjs.org/functions/sprintf:522的团队
- 我
我对window.onload-JQuery用户进行了泛型,请确保使用.ready()API处理程序
<html>
<head>
<script type="text/javascript">
function Clock(id) {
this.id = id;
this.element = document.getElementById(id);
this.element.innerHTML = "00:00:00.000";
this.timeout = 69; //1 = much cpu usage; 1000 = 1 second; 20-70 seem ok.
this.oStartDate=0;
this.instance=0;
}
Clock.prototype = {
readyFor: function(looping) {
if ( (this.instance == 1) && (looping == true) ) {
return true;
} else if ( (typeof looping == 'undefined') && (this.instance == 0) && (this.element.innerHTML == "00:00:00.000") ){
// Initial Call Validated
this.instance = 1;
looping = true;
this.oStartDate = new Date();
//this.oStartDate.setSeconds(this.oStartDate.getSeconds() - 55);
//this.oStartDate.setMinutes(this.oStartDate.getMinutes() - 59);
//this.oStartDate.setHours(this.oStartDate.getHours() - 23);
return true;
}
// Subsequent calls will fail (not allowing duplicate parallel runs on same start button)
return false;
},
startClock: function(looping) {
if ( this.readyFor(looping) ) {
this.element.innerHTML = this.formatClock();
this.loop = setTimeout( this.startClock.bind(this, true), this.timeout );
}
},
formatClock: function() {
var oNowDate = new Date();
var Milliseconds = (oNowDate.getTime() - this.oStartDate.getTime());
return sprintf("%02d:%02d:%02d.%03d",
(Milliseconds / (1000 * 60 * 60) % 24),
(Milliseconds / (1000 * 60) % 60),
((Milliseconds / 1000) % 60),
((Milliseconds / 1000) % 1)*1000);
},
lapClock: function() {
var mainDiv = document.getElementById(this.id);
var newDiv = document.createElement("div");
newDiv.className="lap";
var newContent = document.createTextNode(this.formatClock());
newDiv.appendChild(newContent);
document.body.insertAfter(newDiv, mainDiv);
},
resetClock: function() {
this.element.innerHTML = "00:00:00.000";
this.oStartDate = 0;
this.instance=0;
this.loop = null;
},
stopClock: function() {
clearTimeout(this.loop);
this.oStartDate = 0;
this.instance=0;
this.loop = null;
}
}
function initClock(id) {
value = document.getElementById(id).innerHTML;
if (typeof window[id] == 'undefined') {
window[id] = new Clock(id);
}
}
window.onload = function() {
initClock("clock1");
initClock("clock2");
initClock("clock3");
}
function sprintf(){var a=/%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;var b=arguments,c=0,d=b[c++];var e=function(a,b,c,d){if(!c){c=" "}var e=a.length>=b?"":Array(1+b-a.length>>>0).join(c);return d?a+e:e+a};var f=function(a,b,c,d,f,g){var h=d-a.length;if(h>0){if(c||!f){a=e(a,d,g,c)}else{a=a.slice(0,b.length)+e("",h,"0",true)+a.slice(b.length)}}return a};var g=function(a,b,c,d,g,h,i){var j=a>>>0;c=c&&j&&{2:"0b",8:"0",16:"0x"}[b]||"";a=c+e(j.toString(b),h||0,"0",false);return f(a,c,d,g,i)};var h=function(a,b,c,d,e,g){if(d!=null){a=a.slice(0,d)}return f(a,"",b,c,e,g)};var i=function(a,d,i,j,k,l,m){var n;var o;var p;var q;var r;if(a=="%%"){return"%"}var s=false,t="",u=false,v=false,w=" ";var x=i.length;for(var y=0;i&&y<x;y++){switch(i.charAt(y)){case" ":t=" ";break;case"+":t="+";break;case"-":s=true;break;case"'":w=i.charAt(y+1);break;case"0":u=true;break;case"#":v=true;break}}if(!j){j=0}else if(j=="*"){j=+b[c++]}else if(j.charAt(0)=="*"){j=+b[j.slice(1,-1)]}else{j=+j}if(j<0){j=-j;s=true}if(!isFinite(j)){throw new Error("sprintf: (minimum-)width must be finite")}if(!l){l="fFeE".indexOf(m)>-1?6:m=="d"?0:undefined}else if(l=="*"){l=+b[c++]}else if(l.charAt(0)=="*"){l=+b[l.slice(1,-1)]}else{l=+l}r=d?b[d.slice(0,-1)]:b[c++];switch(m){case"s":return h(String(r),s,j,l,u,w);case"c":return h(String.fromCharCode(+r),s,j,l,u);case"b":return g(r,2,v,s,j,l,u);case"o":return g(r,8,v,s,j,l,u);case"x":return g(r,16,v,s,j,l,u);case"X":return g(r,16,v,s,j,l,u).toUpperCase();case"u":return g(r,10,v,s,j,l,u);case"i":case"d":n=+r|0;o=n<0?"-":t;r=o+e(String(Math.abs(n)),l,"0",false);return f(r,o,s,j,u);case"e":case"E":case"f":case"F":case"g":case"G":n=+r;o=n<0?"-":t;p=["toExponential","toFixed","toPrecision"]["efg".indexOf(m.toLowerCase())];q=["toString","toUpperCase"]["eEfFgG".indexOf(m)%2];r=o+Math.abs(n)[p](l);return f(r,o,s,j,u)[q]();default:return a}};return d.replace(a,i)}
if(!document.insertAfter){document.insertAfter=function(a,b){return(b=b.nextSibling)?this.insertBefore(a,b):this.appendChild(a)};if(this.Node){Node.prototype.insertAfter=document.insertAfter}}
</script>
<style type="text/css">
body, html{font:1em normal monospace;}
div.lap{float:left;background:#fca;padding:0 0.75em;}
div.fl{float:left;}
div.clock{background:#009;color:#eec;padding:0 0.75em;}
div.cl{clear:both;}
</style>
</head>
<body>
<div class="fl"><input type="button" onclick="window['clock1'].startClock();" value="start"><input type="button" onclick="window['clock1'].lapClock();" value="lap"><input type="button" onclick="window['clock1'].stopClock();" value="stop"><input type="button" onclick="window['clock1'].resetClock();" value="reset"></div><div id="clock1" class="fl clock">ERROR</div><div class="cl"></div>
<div class="fl"><input type="button" onclick="window['clock2'].startClock();" value="start"><input type="button" onclick="window['clock2'].lapClock();" value="lap"><input type="button" onclick="window['clock2'].stopClock();" value="stop"><input type="button" onclick="window['clock2'].resetClock();" value="reset"></div><div id="clock2" class="fl clock">ERROR</div><div class="cl"></div>
<div class="fl"><input type="button" onclick="window['clock3'].startClock();" value="start"><input type="button" onclick="window['clock3'].lapClock();" value="lap"><input type="button" onclick="window['clock3'].stopClock();" value="stop"><input type="button" onclick="window['clock3'].resetClock();" value="reset"></div><div id="clock3" class="fl clock">ERROR</div><div class="cl"></div>
</body>
</html>
功能时钟(id){
this.id=id;
this.element=document.getElementById(id);
this.element.innerHTML=“00:00:00.000”;
this.timeout=69;//1=cpu使用率高;1000=1秒;20-70似乎正常。
这个.oStartDate=0;
this.instance=0;
}
Clock.prototype={
readyFor:函数(循环){
if((this.instance==1)和&(looping==true)){
返回true;
}如果((typeof循环=='undefined')&&&(this.instance==0)&&(this.element.innerHTML==“00:00:00.000”){
//初始呼叫已验证
this.instance=1;
循环=真;
this.oStartDate=新日期();
//this.oStartDate.setSeconds(this.oStartDate.getSeconds()-55);
//this.oStartDate.setMinutes(this.oStartDate.getMinutes()-59);
//this.oStartDate.setHours(this.oStartDate.getHours()-23);
返回true;
}
//后续调用将失败(不允许在同一开始按钮上重复并行运行)
返回false;
},
StartLock:函数(循环){
如果(此.readyFor(循环)){
this.element.innerHTML=this.formatClock();
this.loop=setTimeout(this.startClock.bind(this,true),this.timeout);
}
},
formatClock:函数(){
var oNowDate=新日期();
var毫秒=(oNowDate.getTime()-this.oStartDate.getTime());
返回sprintf(“%02d:%02d:%02d.%03d”,
(毫秒/(1000*60*60)%24),
(毫秒/(1000*60)%60),
((毫秒/1000)%60),
((毫秒/1000)%1)*1000);
},
lapClock:function(){
var mainDiv=document.getElementById(this.id);
var newDiv=document.createElement(“div”);
newDiv.className=“lap”;
var newContent=document.createTextNode(this.formatClock());
newDiv.appendChild(newContent);
文档.正文.插入符(newDiv,mainDiv);
},
重置时钟:函数(){
this.element.innerHTML=“00:00:00.000”;
this.oStartDate=0;
this.instance=0;
this.loop=null;
},
stopClock:function(){
clearTimeout(this.loop);
this.oStartDate=0;
this.instance=0;
this.loop=null;
}
}
函数初始化时钟(id){
value=document.getElementById(id).innerHTML;
如果(窗口类型[id]=“未定义”){
窗口[id]=新时钟(id);
}
}
window.onload=函数(){
初始化时钟(“时钟1”);
初始化时钟(“时钟2”);
初始化时钟(“时钟3”);
}
函数sprintf(){var a=/%%\\%(\d+\$)?([-+\'\\\\\\\\\'\\\\*\*\\\\\\\\\\\\\\\\\\\\\\\*\d+)(\.(\*\d+\$\\\\\\\\\\\\\\\\*\d+)
<html>
<head>
<script type="text/javascript">
function Clock(id) {
this.id = id;
this.element = document.getElementById(id);
this.element.innerHTML = "00:00:00.000";
this.timeout = 69; //1 = much cpu usage; 1000 = 1 second; 20-70 seem ok.
this.oStartDate=0;
this.instance=0;
}
Clock.prototype = {
readyFor: function(looping) {
if ( (this.instance == 1) && (looping == true) ) {
return true;
} else if ( (typeof looping == 'undefined') && (this.instance == 0) && (this.element.innerHTML == "00:00:00.000") ){
// Initial Call Validated
this.instance = 1;
looping = true;
this.oStartDate = new Date();
//this.oStartDate.setSeconds(this.oStartDate.getSeconds() - 55);
//this.oStartDate.setMinutes(this.oStartDate.getMinutes() - 59);
//this.oStartDate.setHours(this.oStartDate.getHours() - 23);
return true;
}
// Subsequent calls will fail (not allowing duplicate parallel runs on same start button)
return false;
},
startClock: function(looping) {
if ( this.readyFor(looping) ) {
this.element.innerHTML = this.formatClock();
this.loop = setTimeout( this.startClock.bind(this, true), this.timeout );
}
},
formatClock: function() {
var oNowDate = new Date();
var Milliseconds = (oNowDate.getTime() - this.oStartDate.getTime());
return sprintf("%02d:%02d:%02d.%03d",
(Milliseconds / (1000 * 60 * 60) % 24),
(Milliseconds / (1000 * 60) % 60),
((Milliseconds / 1000) % 60),
((Milliseconds / 1000) % 1)*1000);
},
lapClock: function() {
var mainDiv = document.getElementById(this.id);
var newDiv = document.createElement("div");
newDiv.className="lap";
var newContent = document.createTextNode(this.formatClock());
newDiv.appendChild(newContent);
document.body.insertAfter(newDiv, mainDiv);
},
resetClock: function() {
this.element.innerHTML = "00:00:00.000";
this.oStartDate = 0;
this.instance=0;
this.loop = null;
},
stopClock: function() {
clearTimeout(this.loop);
this.oStartDate = 0;
this.instance=0;
this.loop = null;
}
}
function initClock(id) {
value = document.getElementById(id).innerHTML;
if (typeof window[id] == 'undefined') {
window[id] = new Clock(id);
}
}
window.onload = function() {
initClock("clock1");
initClock("clock2");
initClock("clock3");
}
function sprintf(){var a=/%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;var b=arguments,c=0,d=b[c++];var e=function(a,b,c,d){if(!c){c=" "}var e=a.length>=b?"":Array(1+b-a.length>>>0).join(c);return d?a+e:e+a};var f=function(a,b,c,d,f,g){var h=d-a.length;if(h>0){if(c||!f){a=e(a,d,g,c)}else{a=a.slice(0,b.length)+e("",h,"0",true)+a.slice(b.length)}}return a};var g=function(a,b,c,d,g,h,i){var j=a>>>0;c=c&&j&&{2:"0b",8:"0",16:"0x"}[b]||"";a=c+e(j.toString(b),h||0,"0",false);return f(a,c,d,g,i)};var h=function(a,b,c,d,e,g){if(d!=null){a=a.slice(0,d)}return f(a,"",b,c,e,g)};var i=function(a,d,i,j,k,l,m){var n;var o;var p;var q;var r;if(a=="%%"){return"%"}var s=false,t="",u=false,v=false,w=" ";var x=i.length;for(var y=0;i&&y<x;y++){switch(i.charAt(y)){case" ":t=" ";break;case"+":t="+";break;case"-":s=true;break;case"'":w=i.charAt(y+1);break;case"0":u=true;break;case"#":v=true;break}}if(!j){j=0}else if(j=="*"){j=+b[c++]}else if(j.charAt(0)=="*"){j=+b[j.slice(1,-1)]}else{j=+j}if(j<0){j=-j;s=true}if(!isFinite(j)){throw new Error("sprintf: (minimum-)width must be finite")}if(!l){l="fFeE".indexOf(m)>-1?6:m=="d"?0:undefined}else if(l=="*"){l=+b[c++]}else if(l.charAt(0)=="*"){l=+b[l.slice(1,-1)]}else{l=+l}r=d?b[d.slice(0,-1)]:b[c++];switch(m){case"s":return h(String(r),s,j,l,u,w);case"c":return h(String.fromCharCode(+r),s,j,l,u);case"b":return g(r,2,v,s,j,l,u);case"o":return g(r,8,v,s,j,l,u);case"x":return g(r,16,v,s,j,l,u);case"X":return g(r,16,v,s,j,l,u).toUpperCase();case"u":return g(r,10,v,s,j,l,u);case"i":case"d":n=+r|0;o=n<0?"-":t;r=o+e(String(Math.abs(n)),l,"0",false);return f(r,o,s,j,u);case"e":case"E":case"f":case"F":case"g":case"G":n=+r;o=n<0?"-":t;p=["toExponential","toFixed","toPrecision"]["efg".indexOf(m.toLowerCase())];q=["toString","toUpperCase"]["eEfFgG".indexOf(m)%2];r=o+Math.abs(n)[p](l);return f(r,o,s,j,u)[q]();default:return a}};return d.replace(a,i)}
if(!document.insertAfter){document.insertAfter=function(a,b){return(b=b.nextSibling)?this.insertBefore(a,b):this.appendChild(a)};if(this.Node){Node.prototype.insertAfter=document.insertAfter}}
</script>
<style type="text/css">
body, html{font:1em normal monospace;}
div.lap{float:left;background:#fca;padding:0 0.75em;}
div.fl{float:left;}
div.clock{background:#009;color:#eec;padding:0 0.75em;}
div.cl{clear:both;}
</style>
</head>
<body>
<div class="fl"><input type="button" onclick="window['clock1'].startClock();" value="start"><input type="button" onclick="window['clock1'].lapClock();" value="lap"><input type="button" onclick="window['clock1'].stopClock();" value="stop"><input type="button" onclick="window['clock1'].resetClock();" value="reset"></div><div id="clock1" class="fl clock">ERROR</div><div class="cl"></div>
<div class="fl"><input type="button" onclick="window['clock2'].startClock();" value="start"><input type="button" onclick="window['clock2'].lapClock();" value="lap"><input type="button" onclick="window['clock2'].stopClock();" value="stop"><input type="button" onclick="window['clock2'].resetClock();" value="reset"></div><div id="clock2" class="fl clock">ERROR</div><div class="cl"></div>
<div class="fl"><input type="button" onclick="window['clock3'].startClock();" value="start"><input type="button" onclick="window['clock3'].lapClock();" value="lap"><input type="button" onclick="window['clock3'].stopClock();" value="stop"><input type="button" onclick="window['clock3'].resetClock();" value="reset"></div><div id="clock3" class="fl clock">ERROR</div><div class="cl"></div>
</body>
</html>