Help with setTimeout inside useEffect in Simon's Game

I am trying to do the Simon game and am struggling to get it to play some sounds with 2 seconds between each sound.

Here is the relevant section of my code (it is just my initial attempt, so I will tweak it once I have the sound issue sorted)

  React.useEffect(() => {
    const audios = [
      "https://cdn.freecodecamp.org/curriculum/take-home-projects/simonSound1.mp3",
      "https://cdn.freecodecamp.org/curriculum/take-home-projects/simonSound2.mp3",
      "https://cdn.freecodecamp.org/curriculum/take-home-projects/simonSound3.mp3",
      "https://cdn.freecodecamp.org/curriculum/take-home-projects/simonSound4.mp3"
    ]
    const sequence = [4, 3, 2]
    if (isComputersTurn) {
      sequence.forEach((note) => {
        let audio = new Audio()
        audio.src=audios[note - 1]
        audio.play()
        window.setTimeout(() => {
          console.log(note)
        }, 2000)
      })
    }
  }, [isComputersTurn])

This is intended to fire when isComputersTurn changes state.
The problem is that it just plays the three notes one after the other without any delay - the console.logs all happen at the same time.

I would appreciate any help you could give.

Hi there. Your issue is caused by the forEach loop and the setTimeout being used incorrectly. The loop does not wait for the setTimeout to finish before proceeding to the next iteration, so all the sounds are played almost simultaneously.
To play the sounds with a delay between each, you can use setTimeout in a way that accounts for the sequence’s order.

Thank you. I solved this particular problem by using setInterval.

1 Like