let mainid = document.getElementById("main_id");
function createcards(txt) {
let cards = document.createElement("div");
cards.classList.add("ex-1");
cards.textContent = txt;
return cards;
}
function addElements(parent, children) {
children.forEach((e) => {
setTimeout(() => {
parent.appendChild(e);
}, 1000);
});
}
items = [
createcards(1),
createcards(2),
createcards(3),
createcards(4),
createcards(5),
];
addElements(mainid, items);
I want to append each child one by one. I meant by changing the speed of setTimeout. I tried doing it using for loop but it's not working as expected. please anyone help me?
Seem you a bit misunderstanding about the eventloop and how setTimeout work. Your code will delay 5 function, each 1000ms and then run those at the same time. For more you can check out this link
I tried with setInterval instead, you can check it out to see if it fit your problem
let mainid = document.getElementById("main_id");
function createcards(txt) {
let cards = document.createElement("div");
cards.classList.add("ex-1");
cards.textContent = txt;
return cards;
}
function addElements(parent, children) {
const interval = setInterval(item => {
if (!children.length) {
clearInterval(interval)
return
}
parent.appendChild(children[0])
children.shift()
}, 1000)
}
items = [
createcards(1),
createcards(2),
createcards(3),
createcards(4),
createcards(5),
];
addElements(mainid, items);
<div id="main_id" />
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments