gpt4 book ai didi

javascript - 计数器达到 0 或复位后的清除间隔

转载 作者:行者123 更新时间:2023-11-28 17:11:48 25 4
gpt4 key购买 nike

我正在尝试制作简单的游戏,但我在管理计数器和在计数器达到 0 后清除间隔或单击重置按钮时遇到问题。当它达到 0 时它就可以工作,但是当我尝试将其实现为重置按钮时,计数器正在重置,但随后会以双倍速度运行。

let counter = 60;
let healthPoints = 3;
let points = 0;

document.querySelector('.reset').addEventListener('click', resetGame);


function countTime() {
const timer = document.querySelector('.timer');
const countTime = setInterval(function () {
counter--;
timer.innerHTML = + counter;
if (counter == 0) {
alert('Game over')
clearInterval(countTime);
}
}, 1000)
}

function resetGame() {
newBoard();
counter = 60;
healthPoints = 4;
points = 0;
clearInterval(countTime);
}

最佳答案

您传递给resetGame函数内的clearInterval函数的countTime参数是对名为countTime的函数的引用。您需要重命名该变量并全局声明它:

let counter = 60;
let healthPoints = 3;
let points = 0;
let t = null;
document.querySelector('.reset').addEventListener('click', resetGame);
function countTime() {
const timer = document.querySelector('.timer');
t = setInterval(function () {
counter--;
timer.innerHTML = + counter;
if (counter == 0) {
alert('Game over')
clearInterval(t);
}
}, 1000)
}

function resetGame() {
newBoard();
counter = 60;
healthPoints = 4;
points = 0;
clearInterval(t);
}

关于javascript - 计数器达到 0 或复位后的清除间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54188583/

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