0
let colors = ["red","green","cyan"];
let start = colors[0];
let div = document.getElementById("color");


setInterval(function(){
  document.getElementById("color").style.backgroundColor=colors[0];
  for(var x = 0; x < colors.length; x++){
      document.getElementById("color").style.backgroundColor=colors[x];
      if(colors[x] == colors[colors.length-1]){
          div.style.backgroundColor=start;
          colors[x]++;
      }
    }
},500);

Basically, it loops through the colors but it doesn't reset. What am I actually doing wrong here?

Update:

Thanks to the answer below, I was able to understand what I was doing incorrectly. I've re-written it based on the way I was trying to do it with For Loops.

let colors = ["red","green","cyan","purple","grey"];
let div = document.getElementById("color");

document.getElementById("color").style.backgroundColor=colors[0];

for(let x = 0; x < (colors.length / colors.length); x++){
    var i = x;
    div.style.backgroundColor=colors[i];
}

setInterval(function(){
    div.style.backgroundColor=colors[i];
    i++;
    if(i==colors.length){
        i=0;
    }
},300);

Although inefficient, this is the way I wanted to do it solely for the purpose of testing purposes.

0

1 Answer 1

4

You are running the for loop every 500ms ... but each color change is done within the loop immediately

There's no time for the browser to show anything else but the last background

If what you want to do is simply cycle through those colors, the code is very simple

let colors = ["red","green","cyan"];
let index = 0;
let div = document.getElementById("color");

setInterval(function(){
    div.style.backgroundColor=colors[index];
    index = (index + 1) % colors.length;
},500);
<div id="color">
DIV!
</div>

Sign up to request clarification or add additional context in comments.

4 Comments

Could you explain whats going on here: index = (index + 1) % colors.length;
the modulo operator (remainder after division).... for example 1%3 is 1 - because 1/3 is 0 and 1 remainder ... 2%3 is 2 ... now 3%3 is 0 (1 + remainder 0) - it's a simple way to just keep adding 1 to a number and limit its range to 0...(n-1)
or put another way ... it's a simple way of doing index = index + 1; if (index === colors.length) { index = 0;}
Thank you for the explanation :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.