gpt4 book ai didi

javascript - 如何让这个定时器循环起来? JS

转载 作者:行者123 更新时间:2023-12-02 16:45:38 24 4
gpt4 key购买 nike

  function countdown() {
var secs = 60;
function timer() {
var counter = document.getElementById("counter");
secs--;
counter.innerHTML = "0:" + (secs< 10 ? "0" : "") + String(secs);
if( secs > 0 ) {
setTimeout(timer, 1000);
} else {
alert("Game over, you did not get to finish the game on time :( ");
document.getElementById('memory_board').innerHTML = "";
newBoard();
}
}
timer();
}

countdown();

如何将此代码放入循环中?它基本上是一个计时器,从 60 开始,到 0 结束,当这种情况发生时,游戏重新开始。我重新启动游戏没有问题,但我只是不知道如何将此代码放在循环中。我查看了 codeacademy,它说我必须使用循环

for (var x; y;z ) {
//code
}

其中 x 是起点,y 是终点,z 是变化方式。请帮我解决这个问题,我有点困惑。

最佳答案

您可能想考虑使用setInterval。它每 n 毫秒调用一个给定的函数。您可以像这样构建倒计时函数:

function countdown(seconds) {
var interval = setInterval(function() {
if (seconds < 0) clearInterval(interval); //break the interval
seconds--;
//code
}, 1000); //time in millaseconds to wait
}

关于javascript - 如何让这个定时器循环起来? JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27140772/

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