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);
}
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>
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>