簡體   English   中英

我正在嘗試創建一個航班小部件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM