Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda