'JavaScript Loop only works once

var block = [];

setInterval(function() {

block.push(document.createElement("div"));
for (let i = 0; i < block.length; i++) {

I made a class in css that has some stylings

block[i].setAttribute("class", "block");
document.body.appendChild(block[i]);

}}, 1000);


Solution 1:[1]

var block = [];

setInterval(function() {
  block.push(document.createElement("div"));

  for (let i = 0; i < block.length; i++) {
    block[i].setAttribute("class", "block");
    document.body.appendChild(block[i]);
  }}, 1000);

The reason why it only runs once: You only push one thing to the block array and on the for-loop, the block.length is 1 (because has only one item in it), which is true. Thus, it only gets run once.

According to your question, it sounds like you want to have a function execute a for-loop to update CSS styling.

Advice: Just push all the item or div you wanna update to the block before the for-loop.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 G3N