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

102
Visualizações
Javascript is changing style of all elements instead of one

I am trying to change the background color of div one by one with an interval of 1sec but my code changes the color of all divs after one 1sec

HTML:

<div class="container">
  <div class="bar" id="bar-1"></div>
  <div class="bar" id="bar-2"></div>
  .
  .
  <div class="bar" id="bar-100"></div>
</div>

Javascript:

for (let i = 1; i <= 100; i++) {
  let elem = document.getElementById('bar-' + i);

  setTimeout(function() {
    elem.style.backgroundColor = 'blue';
  }, 1000);
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You're starting all the timeouts at the same time, so they all finish 1 second later.

You need to use different timeouts for each element. Multiply the timeout by the index.

for (let i = 1; i <= 3; i++) {
  let elem = document.getElementById('bar-' + i);

  setTimeout(function() {
    elem.style.backgroundColor = 'blue';
  }, 1000 * i);
}
<div class="container">
  <div class="bar" id="bar-1">1</div>
  <div class="bar" id="bar-2">2</div>
  <div class="bar" id="bar-3">3</div>
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Your current code executes all the elem.style.backgroundColor = 'blue'; lines at approximately the same time, since setTimeout doesn't wait for the previous execution to finish before starting its timer.

The following code should achieve your desired result:

let i = 1;
const itv = setInterval(() => {
  if (i > 3) return clearInterval(itv); // change this number to be 100, 3 is for demo
  const elem = document.getElementById('bar-' + i);
  elem.style.backgroundColor = 'blue';
  i++;
}, 1000);
<div class="container">
  <div class="bar" id="bar-1">1</div>
  <div class="bar" id="bar-2">2</div>
  <div class="bar" id="bar-3">3</div>
</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