gpt4 book ai didi

javascript - 停止计时器不工作:

转载 作者:行者123 更新时间:2023-11-28 19:14:12 30 4
gpt4 key购买 nike

我有THIS我的项目中的计时器。当它用完时,它会显示一个“超时”屏幕,效果很好。但是当玩家游戏结束时,我会显示游戏结束屏幕,但计时器继续运行,当到达 00:00 时,它会切换到“时间已到”屏幕。

如何让这个计时器停止倒计时并再次设置为 00:00?

我尝试添加这样的功能:

CountDownTimer.prototype.stop = function() {
diff = 0;
this.running = false;
};

我也尝试更改innerHTML,但很明显它只是更改数字而不停止计时器,一秒钟后它会再次显示倒计时...我不知道该调用什么。

//Crazy Timer function start
function CountDownTimer(duration, granularity) {
this.duration = duration;
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
}

CountDownTimer.prototype.start = function() {
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj;

(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);

if (diff > 0) {
setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}

obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}());
};

CountDownTimer.prototype.onTick = function(ftn) {
if (typeof ftn === 'function') {
this.tickFtns.push(ftn);
}
return this;
};

CountDownTimer.prototype.expired = function() {
return !this.running;
};

CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};

window.onload = function () {
var display = document.querySelector('#countDown'),
timer = new CountDownTimer(timerValue),
timeObj = CountDownTimer.parse(timerValue);

format(timeObj.minutes, timeObj.seconds);

timer.onTick(format).onTick(checkTime);

document.querySelector('#startBtn').addEventListener('click', function () {
timer.start();
});

function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
}

function checkTime(){
if(this.expired()) {
timeUp();
document.querySelector('#startBtn').addEventListener('click', function () {
timer.start();
});
}
}
};

最佳答案

不要递归调用 setTimeout,而是尝试 setInterval。然后您可以存储对计时器的引用:

this.timer = setInterval(functionToRunAtInterval, this.granularity);

并在游戏结束时杀死它::

clearInterval(this.timer)

(有关 setInterval 的更多信息,请参阅 MDN's docs)

关于javascript - 停止计时器不工作:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30192953/

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