2

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

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

它工作得很好。但问题是当窗口切换或选项卡更改发生时它会停止执行。在提交此问题之前,我阅读了此线程,但未能在我的代码段中实现它。

请帮我一些解决方案或建议..

这是小提琴

4

1 回答 1

2

捕获开始时间(参见Marc 的评论)并跟踪之前的运行(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

于 2012-04-22T18:04:52.557 回答