Javascript 函数中的setInterval保持加速,清除间隔被忽略

Javascript 函数中的setInterval保持加速,清除间隔被忽略,javascript,Javascript,当我激活showMoves时,setInterval应该一次重复一秒钟该功能 但是,几秒钟后它会加速,并在一秒钟内多次激活该功能,而不是一次。此外,即使clearInterval的if语句变为true,clearInterval也不起作用 设i=-1; 函数showMoves{ const start=setIntervalshowMoves,1000; 如果我>game.Computers.length{ clearIntervalstart; } console.logi+''+game.c

当我激活showMoves时,setInterval应该一次重复一秒钟该功能

但是,几秒钟后它会加速,并在一秒钟内多次激活该功能,而不是一次。此外,即使clearInterval的if语句变为true,clearInterval也不起作用

设i=-1; 函数showMoves{ const start=setIntervalshowMoves,1000; 如果我>game.Computers.length{ clearIntervalstart; } console.logi+''+game.computerMoves.length; const showColors=新地图[ [绿色,'石灰'], [黄色,'RGB255255102'], [蓝色,“道奇蓝”], [红色,“鲑鱼”], ]; i++; 让我们移动=游戏; move.style.backgroundColor=showColors.getmove; }
您不应该在setInterval调用的同一个函数中调用setInterval——您正以这种方式设置多个间隔计时器,而不仅仅是一个可以轻松清除的计时器。正如您所说,它正在加速,因为您看到越来越多不同的间隔计时器调用同一个函数。

您正在递归调用showMoves-每秒都会创建一个新的间隔。当函数运行且未达到停止条件时,对刚刚创建的间隔的开始引用将被垃圾收集。您需要一种方法来保存间隔,以便以后可以引用它们,以便清除它们。例如:

let intervals = [];
function showMoves() {
  intervals.push(setInterval(showMoves, 1000));

  if (i > game.computerMoves.length) {
    // clear all currently running intervals:
    intervals.forEach(clearInterval);
    intervals = [];
  }
  // ...

每次setInterval调用showMoves时,都会创建一个新的间隔。它们没有加速,只是在不同的时间有一个以上的开始。考虑改变SET StimetoStimeToOut-StEffType是重复的,并且看起来你的逻辑是为一个一次性的事件而设计的。