Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

93
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda