gpt4 book ai didi

Javascript 计时器问题

转载 作者:行者123 更新时间:2023-11-29 22:24:44 26 4
gpt4 key购买 nike

尝试像下面这样制作一个计时器:

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

最佳答案

捕获开始时间(参见 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

关于Javascript 计时器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10270400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com