0

So I have the following code:

let eventSequence = ['EVENT1', 'EVENT2', 'EVENT3'];

const simulateGame = () => {
   let timer;
   if(!gameStarted) {
      clearTimeout(timer);
      return;
   }
   
   if(eventSequence.length > 0) {
      trackEvents(eventSequence[0]);
      eventSequence.shift();
   } else {
     console.log('The End')
     dispatch(endGame);
   }

  timer = setTimeout(simulateGame, 3000);
}

const trackEvents = (eventCode) => {
   switch (eventCode) {
    case 'EVENT1':
     dispatch(EVENT1(payload));
     break;
    case 'EVENT2':
     dispatch(EVENT2(payload));
     break;
    case 'EVENT3':
     dispatch(EVENT3(payload));
     break;
    default:
     return;
   }
}

useEffect(() => {
   simulateGame();
}, [gameStarted, simulateGame]);

If I run the simulateGame without the trackEvents function and replaced it with a console.log, it behaves as expected where every 3 seconds the event at index 0 is logged to the console and then removed from the array until there are no events left. However when I throw in the trackEvents function, It rushes through the same process without any regards to the delay on the setTimeout. Would appreciate any clarification or any better suggestions for implementing a similar sort of event loop. Cheers!

  • It sounds like simulateGame was called more than once, maybe because gameStarted changed. The code you have to clearTimeout won't work, since the variable `timer` was just declared prior and is empty. So you will end up with multiple active timeouts, if that is indeed the case, which would result in what you are seeing. Check https://stackoverflow.com/questions/53090432/react-hooks-right-way-to-clear-timeouts-and-intervals – James Mar 03 '22 at 13:45
  • Really silly of me but I even forgot to add it when I was writing this question. I had the simualeGame function as a dependency in the useEffect indeed ending up with multiple active timeouts – glengomerson Mar 03 '22 at 21:42

0 Answers0