How to set a delay between forEach loop iteration [solved]

Hi all,

I’m working on my Simon Game and am having some trouble setting a delay between each simon sequence.

I’m wondering, how do you set a delay between each iteration within a forEach loop?
I have tried a million different things with setTimeout and setInterval, but just having no luck!!!

The code in question is as follows:

function computerClick() {
  let computerSequence = gameConfig.moves.computer;
  let maxRounds = gameConfig.round,
      roundCount = 0;
  
  (function next() {
    if (roundCount++ >= maxRounds) return;
    
    setTimeout(() => {
      computerSequence.forEach((tile, index) => {
        buzz(computerSequence[index]);
        console.log("length", gameConfig.round);
      });
      next();
    }, 800);
  })();
}

The full pen is here => http://codepen.io/JackEdwardLyons/pen/PWvQBN

This post helped somewhat, a good find :slight_smile:
http://patrickmuff.ch/blog/2014/03/12/for-loop-with-delay-in-javascript/

1 Like

here is the code that worked

function computerClick() {
  let computerSequence = gameConfig.moves.computer;
  let maxRounds = computerSequence.length,
      roundCount = 0;
  
  const delay = (amount = number) => {
    return new Promise((resolve) => {
      setTimeout(resolve, amount);
    });
  }
  
  async function loop() {
    for (let i = 0; i < maxRounds; i++) {
      buzz(computerSequence[i]);
      console.log("length", gameConfig.round);
      await delay(1000);
    }
    setMessage("message-box","It's your turn!");
    simonTiles.forEach(tile => tile.style.pointerEvents = 'auto');
  }
  loop();
}
1 Like

Are you using TypeScript or NodeJS? It looks like he might be saying in the post you linked that the async/await syntax only works in TypeScript, but I might reading it wrong.

Yeah as a matter of fact, that implementation is using TypeScript but I don’t see why modern ES 7/8 wouldn’t be able to do the same :slight_smile: