Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a new div every 3 seconds

I want divs with circles to be created and appear on my page

I made a create function where I randomly choose a color and add a circle class which gives the shape of a circle

But now I have them all created together, and the quantity is what I indicate

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I make these divs create themselves, let’s say every 3 seconds, and the number of them on the page is almost unlimited?

function createDiv(id, color) {
  let div = document.createElement('div');
  div.setAttribute('id', id);
  if (color === undefined) {
    let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
    div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
  }
  else {
   div.style.backgroundColor = color; 
  }
  div.classList.add("circle");
  document.body.appendChild(div);
}
    
createDiv('first');
createDiv('second');
createDiv('third');
createDiv('fourth');
createDiv('fifth');
createDiv('sixth');
createDiv('seventh');
createDiv('eighth');
createDiv('ninth');
createDiv('tenth');
createDiv('eleventh');
createDiv('twelfth');
div {
  display: inline-block;
  margin: 20px;
}

.circle {
  clip-path: circle(50%);
  height: 50px;
  width: 50px;
  margin: 20px;
}

>Solution :

You can leverage setInterval to run the script every three seconds. Since your id is required, the function I’m running every three seconds below also iterates an i var to leverage and keep unique ids:

function createDiv(id, color) {
  let div = document.createElement('div');
  div.setAttribute('id', id);
  if (color === undefined) {
    let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
    div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
  }
  else {
   div.style.backgroundColor = color; 
  }
  div.classList.add("circle");
  document.body.appendChild(div);
}
    
let i = 0;

const threeSeconds = 3000;

setInterval(() => {
  i += 1;
  createDiv(`div-${i}`)
}, threeSeconds);
div {
  display: inline-block;
  margin: 20px;
}

.circle {
  clip-path: circle(50%);
  height: 50px;
  width: 50px;
  margin: 20px;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading