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

221
Visualizações
Animations won't play in order, but all at once

I am making a Simon-style game and I can get the animation to play the last color in the pattern, but it won't play the entire pattern. I've tried a couple of different things:

function nextTurn() {
  patternComputer.push(getNextColor());
  for (i = 0; i < patternComputer.length; i++) {
    setTimeout(function() {
      animateColor(patternComputer[i]);
      playSound(patternComputer[i]);
    }, 500);
  }
  patternPlayer.length = 0;
}

This one runs through the for loop but doesn't go into the setTimeout function at all until the time has passed, but by then, i isn't correct. I have also tried taking it out of the setTimeout entirely, but that of course makes every animation and sound play at once. How can I make it animate and play the sound of patternComputer[0] and then wait half a second and then play patternComputer[1] and then wait half a second and then play patternComputer[2]...etc. I can't figure out how to just pause the code and let it slowly cycle through each iteration. Is this possible? Should I find a different solution? Thanks! :)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Note that javascript runs in a single thread using the Event Loop.

The problem here is you are registering n timeouts that will be run 500 ms after the main thread registers them. They all will run almost at the same time once those 500 ms pass.

In order to fix your code and make them run 500ms separated you will need to call back your code from the setTimeout. Another simpler solution (but not ideal) would be something like this:

for (i = 0; i < patternComputer.length; i++) {
    setTimeout(function() {
      animateColor(patternComputer[i]);
      playSound(patternComputer[i]);
    }, 500 * (i+1));
  }
about 4 years ago · Juan Pablo Isaza Relatório
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