gpt4 book ai didi

javascript - setInterval 触发过于频繁 (Javascript)

转载 作者:行者123 更新时间:2023-12-03 03:50:44 24 4
gpt4 key购买 nike

我一直在尝试为一个网站编写一个简单的倒计时器代码(请看这里: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);
}

我知道间隔被调用太多次,但我不知道如何修复它。如果有人有解决方案,我将不胜感激。

最佳答案

您应该将 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>

关于javascript - setInterval 触发过于频繁 (Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45177168/

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