Continuous Rainbow color cycling effect in js

Viewed 343

Just started learning JS and want to know how to create an effect in which VIBGYOR color keeps on cycling continuously using JS. Here is my attempt https://jsfiddle.net/2t1kbm8u/.

const scheme = document.querySelector("div");
const rainbow = [
  "#9400D3",
  "#4B0082",
  "#0000FF",
  "#00FF00",
  "#FFFF00",
  "#FF7F00",
  "#FF0000",
];

setInterval(() => {
  for(let colors = 0; colors < rainbow.length; colors++) {
    scheme.style.color = `${rainbow[colors]}`;
    scheme.style.borderColor = `${rainbow[colors]}`;
    console.log(rainbow[colors]);
  }
}, 1000);

Though all colors are being consoled but only the first and last colors are visible

1 Answers
   const scheme = document.querySelector("div");
  const rainbow = [
    "#9400D3",
    "#4B0082",
    "#0000FF",
    "#00FF00",
    "#FFFF00",
    "#FF7F00",
    "#FF0000",
  ];
  var currentColor = 0;
  setInterval(() => {
    scheme.style.color = `${rainbow[currentColor]}`;
    scheme.style.borderColor = `${rainbow[currentColor]}`;
    currentColor++; 
    if (currentColor == rainbow.length-1) {
    currentColor = 0;
    }
  }, 1000);
Related