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
Display divs one by one using setTimeout in js

I'm generating a set of divs using innerHTML.

This is my code.

function generateLights(num){
  for(let i=1;i<=num;i++){
    document.getElementById('lights-container').innerHTML += "<div id='light"+i+"' 
    class='lights'>"+i+"</div>";
    setTimeout(generateLights,1000,num);
  }
 } 

I want to see the divs being created one by one. Just like you see in debugger when you position breakpoint on for the document.getElementById('lights-container').innerHTML += "<div id='light"+i+"' class='lights'>"+i+"</div>"; line.

How would I do that? Where should I position my setTimeout?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I'd dispose of the for...loop and just have setTimeout call the function until the index reaches zero.

const lightsContainer = document.getElementById('lights-container');

function show(index = 5) {
  if (index > 0) {
    const html = `<div class="lights">${index}</div>`;
    lightsContainer.innerHTML += html;
    setTimeout(show, 1000, --index);
  }
}

show();
.lights { width: 100%; background-color: #efefef }
<div id="lights-container"></div>

about 4 years ago · Juan Pablo Isaza Report

0

Since all the timeouts are being created at essentially the same time inside the loop, if you set them to the same time they all finish at the same time.

Instead, you can set each timeout for the time * i. So the first waits 1*time, the second waits 2*time, etc...

const lightsContainer = document.getElementById('lights-container');
const num = 5;

for (let i = 1; i <= num; i++) {
  setTimeout(
    () => (lightsContainer.innerHTML += "<div id='light" + i + "'" + "class='lights'>" + i + '</div>'),
    1000 * i
  );
}
<div id="lights-container"></div>

about 4 years ago · Juan Pablo Isaza Report
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!