我正在尝试在simonGame中产生闪烁效果,并且使这些函数将css的颜色更改为突出显示的颜色,然后又恢复为正常,它们从数组中获取随机序列并更改数组中的颜色:

game.computerMoves = [green, blue, blue, blue, red, red, yellow];

function showMoves () {

  let i = -1;

  const start = setInterval(function(){
  if(i >= game.computerMoves.length-1){
    clearInterval(start);
  }

  console.log(i + 'start ' + 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);
 }, 1000);
}

//revert the colors that were changed in showMoves
function removeMoves() {
  let c = -1;
  //put at 2 seconds to change after showMoves is done
  const computerStop = setInterval(function(){

  console.log(c + 'stop ' + game.computerMoves.length);

  if(c >= game.computerMoves.length-1){
     clearInterval(computerStop);

    }
 const colorKey = new Map([
  [green, 'green'],
  [yellow, 'yellow'],
  [red, 'red'],
  [blue, 'blue']
]);

  c++;

  let move = game.computerMoves[c];

   move.style.backgroundColor = colorKey.get(move);
  }, 2000);
}


并且此函数同时启动它们:

function startFlashing(){
  showMoves();
  removeMoves();
 }


我将removeMoves设置为每2秒启动一次,以便它可以在showMoves完成1秒后激活以创建闪烁效果,但是相反,showMoves首先创建一个闪烁效果,但是showMoves的发射速度比removeMoves快几倍,而不是后一次。其他和showMoves在showMoves已经遍历数组之后触发两次。我将不胜感激。

最佳答案

您可以将其组合为一个计时器,该计时器每秒触发一次,然后相应地切换状态。见下文:



const green = 'GREEN';
const blue = 'BLUE';
const red = 'RED';
const yellow = 'YELLOW';
const game = {
  computerMoves: [green, blue, blue, blue, red, red],
};

const move = document.getElementById('move');

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

const hideColors = new Map([
  [green, 'green'],
  [yellow, 'yellow'],
  [red, 'red'],
  [blue, 'blue'],
]);

const startFlashing = () => {
  let i = -1;
  let visible = true;
  const interval = setInterval(() => {
    if (visible) {
      i += 1;
    }

    if (i >= game.computerMoves.length) {
      clearInterval(interval);
      return;
    }

    visible = !visible;
    colorMapper = visible ? showColors : hideColors;
    const turn = game.computerMoves[i];
    const color = colorMapper.get(turn);
    console.log(`visible: ${visible}, color: ${turn}`);
    move.style.backgroundColor = color;

  }, 1000);
}

startFlashing();

#move {
  width: 100px;
  height: 100px;
  border: 2px solid black;
}

<html>
  <body>
    <div id="move"></div>
  </body>
</html>

关于javascript - 两个setIntervals没有按顺序激活并在不同时间触发,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49926205/

10-11 14:11