函数中的setInterval保持超速,忽略清除间隔

时间:2018-04-19 01:43:24

标签: javascript

当我激活showMoves()时,setInterval应该一次重复一次这个功能。

但是,它会在几秒钟后加速并在一秒钟内激活该功能几次而不是一次。即使clearInterval语句变为iftrue也无法正常工作。

let i = -1;

function showMoves() {
  const start = setInterval(showMoves, 1000);

  if (i > game.computerMoves.length) {
    clearInterval(start);
  }

  console.log(i + ' ' + game.computerMoves.length);

  const showColors = new Map([
    [green, 'lime'],
    [yellow, 'rgb(255,255,102)'],
    [blue, 'dodgerblue'],
    [red, 'salmon'],
  ]);

  i++;

  let move = game.computerMoves[i];

  move.style.backgroundColor = showColors.get(move);

}

2 个答案:

答案 0 :(得分:1)

你不应该在setInterval调用的同一个函数中调用setInterval - 你正在设置多个间隔定时器,而不仅仅是你可以轻松清除的定时器。正如你所说,它正在“加速”,因为你看到越来越多不同的间隔定时器调用相同的功能。

答案 1 :(得分:0)

您递归调用showMoves - 每隔一秒创建一个新间隔。当函数运行并且达到停止条件 时,您刚刚创建的间隔的start引用只是垃圾回收。您需要一种方法来保存间隔,以便稍后可以引用它们以便清除它们。例如:

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

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