setInterval的正确位置

The*_*arp 0 javascript setinterval

我似乎在我的代码中找不到setinterval()的正确用法。它应该每秒刷新9种新的随机颜色。

我已经尝试将代码放置在带有嵌套循环的箭头函数中,希望这将为完成的每个循环启动间隔。

但是,这并没有解决任何问题。请参考下面的完整代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

Que*_*tin 5

setInterval会每秒生成一次div,但test();递归调用只会无限运行它,并且永远不会让DOM更新。然后超出了调用堆栈,脚本消失了。

不要test()递归调用。说它只是从setInterval。

然后,您需要给div元素一些高度,以便可以有一些像素来渲染背景色。

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);
}
Run Code Online (Sandbox Code Playgroud)
div { display: inline-block; height: 10px; width: 10px; }
Run Code Online (Sandbox Code Playgroud)