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!