Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

94
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda