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

210
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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