Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

92
Views
setTimeout rushes through switch statement

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!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!