[英]I am trying to create a flight widget
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);
我要 append 每个孩子一个一个。 我的意思是改变 setTimeout 的速度。 我尝试使用 for 循环来做,但它没有按预期工作。 请有人帮助我吗?
您必须创建立即调用的 function 表达式(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 的工作方式有点误解。 您的代码将延迟 5 个 function,每 1000 毫秒,然后同时运行它们。 有关更多信息,您可以查看此链接
我尝试使用 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" />
我找到了另一种解决方案,根据需要使用 setTimeout 。 这里我改变的是使用for... of
而不是forEach
。 我刚刚在尝试解决您的问题时发现, forEach
不适用于异步 function。 参考: 在 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" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.