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

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

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 Denunciar

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