I'm generating a set of divs using innerHTML.
This is my code.
function generateLights(num){
for(let i=1;i<=num;i++){
document.getElementById('lights-container').innerHTML += "<div id='light"+i+"'
class='lights'>"+i+"</div>";
setTimeout(generateLights,1000,num);
}
}
I want to see the divs being created one by one. Just like you see in debugger when you position breakpoint on for the document.getElementById('lights-container').innerHTML += "<div id='light"+i+"' class='lights'>"+i+"</div>"; line.
How would I do that? Where should I position my setTimeout?
I'd dispose of the for...loop and just have setTimeout call the function until the index reaches zero.
const lightsContainer = document.getElementById('lights-container');
function show(index = 5) {
if (index > 0) {
const html = `<div class="lights">${index}</div>`;
lightsContainer.innerHTML += html;
setTimeout(show, 1000, --index);
}
}
show();
.lights { width: 100%; background-color: #efefef }
<div id="lights-container"></div>
Since all the timeouts are being created at essentially the same time inside the loop, if you set them to the same time they all finish at the same time.
Instead, you can set each timeout for the time * i. So the first waits 1*time, the second waits 2*time, etc...
const lightsContainer = document.getElementById('lights-container');
const num = 5;
for (let i = 1; i <= num; i++) {
setTimeout(
() => (lightsContainer.innerHTML += "<div id='light" + i + "'" + "class='lights'>" + i + '</div>'),
1000 * i
);
}
<div id="lights-container"></div>