我一直在尝试为一个简单的倒数计时器编写代码,我正在为网站制作(看看这里:sbtimescore.github.io)。不幸的是,我遇到了一个逻辑错误,我的有限知识无法解决(我是新手)。当重复按下开始/暂停时,计时器开始加速。我已经发布了以下运行onclick()的代码:
function spGameClock() {
if (gameClockRunning == false) {
gameClockRunning = true;
} else {
gameClockRunning = false;
return;
}
function timer() {
if (gameCounter == 0) {
clearInterval(interval);
$("#GameClockText").html(secondsToText(gameCounter));
blinkIt("GameClockBox");
} else if (gameCounter > 0 && gameClockRunning == true) {
$("#GameClockText").html(secondsToText(gameCounter));
gameCounter = gameCounter - 1;
} else if (gameCounter > 0 && gameClockRunning == false) {
clearInterval(interval);
} else {}
}
var interval = setInterval(timer, 1000);
}
我知道间隔被调用了太多次,但我不确定如何修复它。如果有人有解决方案,我将不胜感激。
答案 0 :(得分:1)
您应该将interval
定义为spGameClock
函数之外的变量。一个好的地方是jQuery ready
回调。然后,您也可以使用该变量本身来确定时钟是否正在滴答。
以下是使用countdownjs的实现:
$(function () {
var interval = null, // define outside of spGameClock scope
gameCounter = 10; // Some initial value
function spGameClock() {
// Use interval as detection:
if (interval == null) {
interval = setInterval(timer, 1000);
$("#GameClockText").text(secondsToText(gameCounter));
} else {
clearInterval(interval);
interval = null; // Always set to null after clearing
$("#GameClockText").text(secondsToText(gameCounter) + " (paused)");
}
function timer() {
gameCounter--;
$("#GameClockText").text(secondsToText(gameCounter));
// No need to test interval for null here, since it certainly is not.
if (gameCounter <= 0) {
clearInterval(interval);
interval = null;
blinkIt("GameClockBox");
}
}
}
// Attach event handler here instead of using onclick attribute
$("#toggle").click(spGameClock);
// Start clock now
spGameClock();
// Utility functions:
function secondsToText(sec) { // Uses countdown library:
return countdown(new Date().getTime() + 1000*sec).toString() || "Game Over!";
}
function blinkIt(id) {
(function loop(times) {
if (times) $('#' + id).fadeToggle(400, loop.bind(null, times-1));
})(6);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/countdown/2.6.0/countdown.min.js"></script>
<button type="button" id="toggle">Pause/Continue</button>
<div id="GameClockBox">
<div id="GameClockText"></div>
</div>