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

127
Vistas
How do you create a delay inside a recursive loop in javascript?

So I was trying to create a visual representation of bubble sort using some CSS animations and JS. The animation is supposed to have 10 numbers in bubbles, and the bubbles will float up get compared and swapped if necessary. The problem I have is I can't seem to delay the animations to actually let individual bubbles float while the rest are dormant. I tried using recursive loops that take the indexes of the array and give individual elements the "bounce" animation, and another function that gets rid of the animation after some time. Here is the code.

function animateUp(index){
    if(index < 9){
       document.getElementById("elem-" + index).style.animation = "bounce 500ms";
       document.getElementById("elem-" + index+1).style.animation = "bounce 500ms";
       setTimeout(stopAnimationByIndex(index), 600);
       setTimeout(stopAnimationByIndex(index+1), 600);
    }
    else{
        return;
    }
    
    setTimeout(animateUp(index + 1), 700);
}

function sort(){
    animateUp(0);
}
@keyframes bounce {
    0% {
        transform: translateY(0px);
        
    }
    50% {
        transform: translateY(-20px);
    }
    100%{
        transform: translateY(0px);
    }
}
<div class="visual-rep">
        <div class="arr-container">
            <div class="arr" id="elem-0"></div>
            <div class="arr" id="elem-1"></div>
            <div class="arr" id="elem-2"></div>
            <div class="arr" id="elem-3"></div>
            <div class="arr" id="elem-4"></div>
            <div class="arr" id="elem-5"></div>
            <div class="arr" id="elem-6"></div>
            <div class="arr" id="elem-7"></div>
            <div class="arr" id="elem-8"></div>
            <div class="arr" id="elem-9"></div>
        </div>
        <br>
        <br>
        <button class="sort" onclick="sort()">Sort</button>
</div>

I later call the function when a button is clicked. The animation doesn't work and there is no delay in the animation all the bubbles are assigned the animation at the same time and there is no delay between them. This doesn't seem to work so is there an another way for me to do this?

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