Javascript计时器问题

时间:2012-04-22 17:42:13

标签: javascript jquery

尝试按照以下方式制作计时器:

HTML:

<div id="timer">
     <span id="minute" class="dis">00</span> :
     <span id="second" class="dis">00</span> :
     <span id="milisecond" class="dis">00</span>
 </div>

 <input type="button" value="Start/Stop" id="startStop" />
 <input type="button" value="Reset" id="reset" />

jQuery的:

 var a = false,
         t = null,
         ms = 0,
         s = 0,
         m = 0,
         dl = 10,
         now = null,
         before = new Date(),
         El = function(id) { return document.getElementById(id);};

     function dsp() {
         if(ms++ == 99){
              ms = 0;
             if(s++ == 59) {
                 s = 0;
                 m++;
             } else s = s;
         } else ms = ms;    
         El('milisecond').innerHTML = ms
         El('second').innerHTML = s < 10 ? '0' + s : s;
         El('minute').innerHTML = m < 10 ? '0' + m : m;
     }

     function r() {
         a = true;
         var els = document.getElementsByClassName('dis');
         ms = s = m = 0;
         sw();        
         for(var i in els)  {
             els[i].innerHTML = '00';    
         }
     }

     function sw() {
         a ? clearInterval(t) : t = setInterval(dsp, dl);
         a = !a;
     }
     El('startStop').addEventListener('click', sw, true);
     El('reset').addEventListener('click', r, true);

它运作得很好。但问题是当窗口切换或标签发生变化时它会停止执行。在提交此问题之前,我已阅读this thread,但未能在我的代码段中实现它。

请帮我解决一些问题或建议..

以下是fiddle

1 个答案:

答案 0 :(得分:2)

捕获开始时间(请参阅Marc's comment)并跟踪之前的运行(offset):

var a = false;
var dl = 10;
var El = function(id) { return document.getElementById(id);};
var start = null; // starting time of current measurement
var offset = 0;   // offset for previous measurement

function dsp() {
    var tmp = new Date(new Date() - start + offset ); // calculate the time
    var ms = tmp.getMilliseconds();
    var m = tmp.getMinutes();
    var s = tmp.getSeconds();
    El('milisecond').innerHTML = ms;
    El('second').innerHTML = s < 10 ? '0' + s : s;
    El('minute').innerHTML = m < 10 ? '0' + m : m;
}

function r() {
    a = true;
    var els = document.getElementsByClassName('dis');    
    sw();
    offset = 0; // Clear the offset
    for(var i in els)  {
        els[i].innerHTML = '00';    
    }
}

function sw() {
    if(a){
    // If the timer stops save the current value
        offset += (new Date()) - start;
    }else
        start = new Date();
    a ? clearInterval(t) : t = setInterval(dsp, dl);
    a = !a;
}
document.getElementById('startStop').addEventListener('click', sw, true);
document.getElementById('reset').addEventListener('click', r, true);

JSFiddle