Let's say I have a html grid of 100 span elements and I want to gradully change the colour of these spans from span[0] to span[100]. My code below changes the colour of the span elements but all in one hit, and then again after 3 seconds but does not do what I'm after. Ideally I would like it gradually change the colours then after 3 seconds start changing them again whilst the first function keeps changing to the end of span[100]
var count = 1;
var ancestor = document.getElementById('hello');
var descendents = ancestor.getElementsByTagName('span');
var myColors = ['rgb(146, 168, 209)', 'rgb(136, 176, 75)', 'rgb(247, 202, 201)'];
var e, c;
function myLoop(count) {
setTimeout(function() {
for (i = 0; i < descendents.length; ++i) {
e = descendents[i];
c = e.style.color;
//pick color
e.style.color = myColors[Math.floor(Math.random() * myColors.length)];
}
count++;
if (count < descendents.length) {
myLoop(count);
}
}, 3000);
}
myLoop(count);
The code below could use some improving and syntax sugar to be smaller, but I think that's what you are looking for. In this snippet I created only 10 spans and set the interval to 250m just to be easier to test. What it will do is start from span 1 and go until 10 changing the colors to the first one in myColors array. After it finishes, it will begin again from the second color and so forth.
In your code you used setTimeout, that will run once after 3s and then not run again. I think that you were looking for setInterval, which will create a loop that runs every X miliseconds.
const myColors = ['rgb(146, 168, 209)', 'rgb(136, 176, 75)', 'rgb(247, 202, 201)'];
let index = 0;
let loops = 0;
function generateSpans(){
const ancestor = document.getElementById("ancestor");
for(let i = 0; i<10; i++){
const span = document.createElement("span");
span.innerText = i;
ancestor.appendChild(span);
}
}
function blinkElements(){
const elements = document.getElementsByTagName("span");
setInterval(function(){
if(index === elements.length){
index = 0;
if(loops === myColors.length-1){
loops = 0;
}else{
loops++;
}
}
elements[index].style.backgroundColor = myColors[loops];
index++;
}, 250);
}
document.addEventListener("DOMContentLoaded", function(event) {
generateSpans();
blinkElements();
});
div {
width: 1000px;
height: 50px;
}
span {
background-color: red;
padding: 10px;
margin: 10px;
}
<div id="ancestor">
</div>