我有两个函数,一个是点击开始按钮触发的
function startGame() {
setInterval(setCellPosition, 3000);
setTimeGame = setTimeout(startGame, 2000);
setTime();
};
第二个,点击重置按钮后调用
function resetGame() {
scoreBox.innerHTML = "0";
timeBox.innerHTML = "60";
liveBox.innerHTML = "3";
clearTimeout(setTimeGame)
};
resetGame
函数不起作用。值(分数、时间、直播)已重置,但 startGame
函数不会停止。如何解决?如何停止 startgame
函数?
最佳答案
虽然您应该重新考虑您的算法,因为您目前拥有的用于启动和停止游戏的算法有点复杂。
但是,此解决方案背后的想法是存储您所有的 timeouts和 interval数组中的对象。当发生重置时,您将遍历每个对象并将其停止。
然后你重置数组。
const sts = []; //all set timeouts and intervals
function startGame() {
sts.push(setInterval(setCellPosition, 3000));
sts.push(setTimeout(startGame, 2000));
setTime();
};
function resetGame() {
scoreBox.innerHTML = "0";
timeBox.innerHTML = "60";
liveBox.innerHTML = "3";
sts.forEach(clearTimeout);
sts.length = 0;
};
根据 MDN:
The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout(); this value can be passed to clearTimeout() to cancel the timeout.
It may be helpful to be aware that setTimeout() and setInterval() share the same pool of IDs, and that clearTimeout() and clearInterval() can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code.
关于javascript - 如何停止调用函数 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54277835/