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

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

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 Denunciar

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