我正在尝试创建一个飞行小部件


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);

我想把每个孩子一个接一个地附加上去。我的意思是改变setTimeout的速度。我试着用for循环来做,但并没有像预期的那样工作。有人帮我吗?

您似乎对事件循环和setTimeout的工作方式有点误解。您的代码将延迟5个函数,每个函数延迟1000ms,然后同时运行这些函数。要了解更多信息,您可以查看此链接

我尝试了setInterval,你可以看看它是否适合你的问题

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" />

您必须创建立即调用的函数表达式(IIFE(来围绕setTimeout创建闭包。

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, i) => {
(function(index) {
setTimeout(function() { parent.appendChild(e); }, i * 1000);
})(i);
});
}
items = [
createcards(1),
createcards(2),
createcards(3),
createcards(4),
createcards(5),
];
addElements(mainid, items);
<div id="main_id" />

我找到了另一个解决方案,可以随心所欲地使用setTimeout。这里我所更改的是使用for ... of而不是forEachforEach将无法使用异步函数,因为我刚刚在尝试解决您的问题时发现了这一点。参考:使用带有forEach循环的async/await

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 sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function addElements(parent, children) {
for (let e of children) {        
await sleep(1000);
parent.appendChild(e); 
}
}
items = [
createcards(1),
createcards(2),
createcards(3),
createcards(4),
createcards(5),
];
addElements(mainid, items);
<div id="main_id" />

最新更新