Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!