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

164
Visualizações
Why does my page get rendered all at once?

My understanding is that the event loop can get a bit complicated. I'm fairly new to JavaScript and the web in general so it's even more complicated for me. However, I have a made a grid on the screen using grid layout. All I wanted to do was to fill each box with red color but I'd like to see this filling happen. What happens instead is that the loop is being computed and then everything gets rendered at the same time. How can I manage to make it look like an animation of some sort? Maybe point towards some resource so I can read about this? I searched for event loop, loops and renders but found way too much information. Any help thanks in advance!

for(let i = 1; i < 100; i += 2){
    setTimeout(() =>{
        const squareElement = document.querySelector('.grid :nth-child('+i+')');
        console.log('.grid:nth-child('+i+')');
        squareElement.style.backgroundColor = 'red';  
    }, 2000 );
}

There's my code. As you can see I even put a setTimeout so I can render one by one.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your code doesn't do what you expect it to do. You are expecting your code to run, wait 2-seconds, repeat 99 times.

for 1 to 100
 update one element to be red
 wait 2 seconds

Instead your code queues itself up to run 100 times, after waiting 2-seonds.

wait 2 seconds
for 1 to 100
 update one element to be red

A solution would to run your update element function, and at the end of execution, queue itself to run again after 2 seconds. Once it's modified all 100 elements, no longer set itself to run again.

function updateElement(i) {
   const squareElement = document.querySelector('.grid :nth-child('+i+')');
   console.log('.grid:nth-child('+i+')');
   squareElement.style.backgroundColor = 'red'; 
 

   // if there are more elements to update, run again after 2 seconds.
   if(i < 100) {
     setTimeout(()=>updateElement(++i),2000);
   }
}

// start the function after 2 seconds.
setTimeout(()=>updateElement(0),2000);
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