如何停止调用函数 JS

How to stop calling a function JS

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

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 and 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.

如果您将 setInterval 替换为 gameOver 标志和包含 setTimeoutwhile 循环,例如:

let gameOver = false;
function startGame() {
  while(gameOver == false){
    setTimeout(setCellPosition, 3000);
  }
   // Note: It seems strange that you're recursively calling `startGame` here
  setTimeGame = setTimeout(startGame, 2000);
  setTime();
};

...然后在你的resetGame函数中,你可以设置gameOver = true停止循环;