[英]Javascript Countdown Timer goes too fast even with boolean switch
我在 javascript 中有以下倒计时 function:
countdownTimer() {
// exit method if it is active
if(this.isCountdownActive == true){
return;
}
// first time set true
this.isCountdownActive = true
this.countdown = 10
// Define the work to be done
var doWork = () => {
if(this.countdown <= 0) {
ticker.stop();
this.countdown = 10
this.isCountdownActive = false
if (this.thisUser.captain) {
Store.submitTurnEnd();
}
}
this.countdown -= 1;
};
// Define what to do if something goes wrong
var doError = function() {
console.warn('The drift exceeded the interval.');
};
// (The third argument is optional)
var ticker = new Util.AdjustingInterval(doWork, 1000, doError);
ticker.start()
},
这里是调整间隔 function
function AdjustingInterval(workFunc, interval, errorFunc) {
var that = this;
var expected, timeout;
this.interval = interval;
this.start = function() {
expected = Date.now() + this.interval;
timeout = setTimeout(step, this.interval);
}
this.stop = function() {
clearTimeout(timeout);
}
function step() {
var drift = Date.now() - expected;
if (drift > that.interval) {
// You could have some default stuff here too...
if (errorFunc) errorFunc();
}
workFunc();
expected += that.interval;
timeout = setTimeout(step, Math.max(0, that.interval-drift));
}
}
我相信这应该可以工作,但是计时器有时仍然运行得太快并且无法正确重置。 我会说 75% 的时间它工作正常,但在我点击后它变得“跳跃”并且速度太快。 此外,计时器没有正确停止。 使其不断循环。
谢谢您的帮助。
只需将 ms 调整为您想要的精确度
const span = document.getElementById("t"); let d = new Date(); d.setHours(d.getHours()+1); // demo time let tId = setInterval(() => span.innerText = new Date(d.getTime()-new Date().getTime()).toLocaleTimeString(),100)
<span id="t"></span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.