javascript - 如何停止调用函数 JS

标签 javascript settimeout setinterval

我有两个函数,一个是点击开始按钮触发的

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 函数?

最佳答案

虽然您应该重新考虑您的算法,因为您目前拥有的用于启动和停止游戏的算法有点复杂。

但是,此解决方案背后的想法是存储您所有的 timeoutsinterval数组中的对象。当发生重置时,您将遍历每个对象并将其停止。

然后你重置数组。

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/

相关文章:

javascript - 自动填充预定值的输入框

javascript - 避免在通过 AutoTag(文本标记算法)生成的数组中使用同义词

javascript - 将变量传递给javascript函数的问题

javascript - 如何将 React 的 getDerivedStateFromProps 与 setTimeout 一起使用?

javascript - .addEventListener 中的计时器不起作用?

javascript - 防止 Atom Beautify 自动格式化 es6 导入/对象解构 (React)

javascript - 如何停止一个自调用的 setTimeout() 函数?

javascript - 数组上的setInterval

Javascript - 自动启动/停止 setInterval

javascript - clearInterval 无法正常运行