TheAlphaKarp
TheAlphaKarp

Reputation: 209

correct placement of setInterval

I can't seem to find the correct use of the setinterval() in my code. It should refresh every second with 9 new random colors.

I already tried to place my code in an arrow function with a nested loop, hoping that this would initiate the interval for every loop it completes.

This however hasn't solved anything. Reference the full code down below:

let test = () => {
  for (let i = 0; i <= 9; i++) {
    addRandomColorToSquare();
  }
}

setInterval(test, 1000);


let addSquareToDOM = function(color) {
  let square = document.createElement('div');
  square.className = 'square';
  square.style.backgroundColor = color;
  document.body.appendChild(square);
}

let addRandomColorToSquare = function() {
  const randomRed = Math.floor(Math.random() * 256);
  const randomGreen = Math.floor(Math.random() * 256);
  const randomBlue = Math.floor(Math.random() * 256);

  let rgbColor = `rgb(${randomRed}, ${randomGreen}, ${randomBlue})`;

  addSquareToDOM(rgbColor);
  test();
}

Upvotes: 0

Views: 46

Answers (1)

Quentin
Quentin

Reputation: 943608

setInterval will generate the divs every second, but calling test(); recursively will just run it infinitely and never let the DOM update. Then the callstack is exceeded and the script dies.

Don't call test() recursively. Call it only from setInterval.

Then you need to give the div elements some height so you can have some pixels to render the background colours on.

let test = () => {
  for (let i = 0; i <= 9; i++) {
    addRandomColorToSquare();
  }
}

setInterval(test, 1000);


let addSquareToDOM = function(color) {
  let square = document.createElement('div');
  square.className = 'square';
  square.style.backgroundColor = color;
  document.body.appendChild(square);
}

let addRandomColorToSquare = function() {
  const randomRed = Math.floor(Math.random() * 256);
  const randomGreen = Math.floor(Math.random() * 256);
  const randomBlue = Math.floor(Math.random() * 256);

  let rgbColor = `rgb(${randomRed}, ${randomGreen}, ${randomBlue})`;

  addSquareToDOM(rgbColor);
}
div { display: inline-block; height: 10px; width: 10px; }

Upvotes: 5

Related Questions