1 回答

TA貢獻1780條經驗 獲得超4個贊
如果你想循環fplDeltas并調用drawChart每個增量,間隔一秒,你可以這樣做:
// So we skip the `sleep` the first time
let first = true;
for (const delta of fplDeltas) {
// Sleep on all but the first
if (first) {
first = false;
} else {
await sleep(1000);
}
// Draw the chart
drawChart(delta);
}
由于這是在一個async函數中,因此await sleep(1000)(注意:not delay,您的基于 promise 的sleep)讓瀏覽器允許它進行任何繪圖等。
這是一個簡單的示例,只需在其中添加一個 DOM 元素drawChart:
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function example() {
const fplDeltas = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let first = true;
for (const delta of fplDeltas) {
// Sleep on all but the first
if (first) {
first = false;
} else {
await sleep(1000);
}
// Draw the chart
drawChart(delta);
}
}
function drawChart(delta) {
const div = document.createElement("div");
div.textContent = delta;
document.body.appendChild(div);
}
(async () => {
try {
await example();
console.log("Done");
} catch (e) {
console.error("Error:", e);
}
})();
添加回答
舉報