Javascript 计时器以2而不是1计数
我用html/css/javascript编写了这个扫雷游戏,它通常运行得相当不错,我在里面放了一个计时器,计时器总是平稳运行 然而,当我随机播放时,它开始增加两次(这意味着计时器不知何故被触发了两次,但没有超时工作)。据我所知,这以前从未发生过,我尝试过,但无法再次发生,以下是相关代码:Javascript 计时器以2而不是1计数,javascript,timer,Javascript,Timer,我用html/css/javascript编写了这个扫雷游戏,它通常运行得相当不错,我在里面放了一个计时器,计时器总是平稳运行 然而,当我随机播放时,它开始增加两次(这意味着计时器不知何故被触发了两次,但没有超时工作)。据我所知,这以前从未发生过,我尝试过,但无法再次发生,以下是相关代码: function timer() { if ( gameOn ) { timePast++; document.getElementById("timer").inne
function timer() {
if ( gameOn ) {
timePast++;
document.getElementById("timer").innerHTML = timePast;
timeoutID = window.setTimeout(timer, 1000);
}
}
计时器在mystart()函数中设置:
timePast = 0;
//start the timer if it was stopped
if ( !gameOn )
timeoutID = window.setTimeout(timer, 1000);
下面是我的gameOn
变量的所有实例(除了上面和if语句中的两个):
以下是上述功能的部分(可能相关的部分):
function bombCheck(event) {
var boxNum = parseInt(event.id);
if ( bomb.indexOf(boxNum) >= 0 ) {
gameOver(); }}
gameOver(){gameOn = false;}
现在是checkWin:
function checkWin() {
if ( flippedCount === ( cellAmount - bombAmount ) ) { gameOn = false; }}
启动触发器:
<input type="button" class="MtopSmall" value="start!" name = "startButton" onclick = "start();" >
start(){gameOn = true;}
start(){gameOn=true;}
我知道我应该把setTimeout
改成setInterval
,我会的(总有一天),但我想知道这里出了什么问题
我对javascript有相当好的理解,我完全被难住了,如果有人能告诉我为什么会发生这种情况和/或如何修复它,那就太酷了。“我知道我应该将setTimeout
更改为setInterval
…”不一定。我几乎总是更喜欢链式setTimeout
而不是setInterval
。您的代码都被切碎了,您引用的函数(如checkWin
)没有显示。这使得帮助你变得非常困难。请在单个连续代码块中发布相关代码。只需省略未更新的代码。理想情况下,制作一个.@T.J.Crowder我对这两种方式都没有偏好,但我想知道你为什么这么做:)@TryingToGetProgrammingDirect:不,你不能指望人们通过随机链接来帮助你,而非现场资源会腐烂,使问题在将来对其他人毫无用处。更多信息:@naomik:setInterval
过去在不同浏览器中是不一致的(例如,间隔是从每次函数调用的开始还是结束测量的)。我刚刚在setTimeout
方面运气更好,所以我已经习惯了,所以这就是我一直在做的…:-)
<input type="button" class="MtopSmall" value="start!" name = "startButton" onclick = "start();" >
start(){gameOn = true;}