我正在嘗試制作一個向網頁添加文本的程式,如下所示:
Hello
Morning
Morning
Morning
Morning
Evening
應該有:
- “Hello”和第一個“Morning”之間有 5 秒的延遲。
- 每個“早上”之間有 5 秒的延遲。
- 最后一個“早上”和“晚上”之間有 6 秒的延遲。
這是我目前所掌握的全部 HTML 和 JavaScript。
function notify(msg, loops, taskTime) {
var ul = document.getElementById("notifications");
for (let i = 0; i < loops; i ) {
(function(i) {
window.setTimeout(function() {
var li = document.createElement("li")
li.appendChild(document.createTextNode(`${msg}`));
ul.appendChild(li)
}, taskTime * i)
}(i))
}
}
notify('Hello', 1, 5000)
notify('Morning', 4, 5000)
notify('Evening', 1, 6000)
<div>
<ul id="notifications" style="list-style-type:none;margin-left:10%;"></ul>
</div>
我的問題是在加載網頁時,輸出是:
Hello
Morning
Evening
Morning
Morning
Morning
如何確保函式按照我想要的順序運行,而不是這種混合輸出?前 3 個輸出也立即出現,而不是延遲出現。我該如何避免呢?
uj5u.com熱心網友回復:
乘以毫秒數,以便為后面的 setTimeout 分配正確的時間。taskTime此外,您將and相乘i,它始終為 0。我改為替換i為i 1。
試試這個 JavaScript 代碼(它有效):
function notify(msg, loops, taskTime) {
var ul = document.getElementById("notifications");
for (let i = 0; i < loops; i ) {
(function (i) {
window.setTimeout(function () {
var li = document.createElement("li")
li.appendChild(document.createTextNode(`${msg}`));
ul.appendChild(li)
}, taskTime * (i 1))
}(i))
}
}
notify('Hello', 1, 5000)
notify('Morning', 4, 5000 * 2)
notify('Evening', 1, 6000 5000 * 6)
uj5u.com熱心網友回復:
根據邁克的評論:
tasks = [
{message: 'Hello', delay: 5000},
{message: 'Morning', delay: 5000},
{message: 'Morning', delay: 5000},
{message: 'Morning', delay: 5000},
{message: 'Morning', delay: 5000},
{message: 'Evening', delay: 6000},
]
function runTask(index) {
var ul = document.getElementById("notifications");
var li = document.createElement("li");
li.appendChild(document.createTextNode(`${tasks[index].message}`));
ul.appendChild(li);
if(index < tasks.length - 1){
setTimeout( () => runTask(index 1), tasks[index].delay);
}
}
if(tasks.length > 0) runTask(0); //make sure the task list has at least one element.
uj5u.com熱心網友回復:
在現代 JavaScript 中,async函式可能應該是您撰寫異步代碼時的第一個呼叫埠。它們更清晰,通常更容易理解。
在下文中,delay承諾setTimeout.
notifyli在回圈中向檔案添加元素,并在每次迭代開始時添加延遲。
我不確定這是否符合您對第一個的需要"Hello"。
const delay = (ms) => new Promise((res) => setTimeout(res, ms))
const ul = document.getElementById("notifications")
async function notify(msg, count, ms) {
for (let i = 0; i < count; i ) {
await delay(ms)
const li = document.createElement('li')
li.innerText = `${msg} ${Date()}`
ul.appendChild(li)
}
}
(async () => {
await notify('Hello', 1, 5000)
await notify('Morning', 4, 5000)
await notify('Evening', 1, 6000)
})()
<p>Notifications will appear below:</p>
<ul id="notifications"></ul>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/523709.html
上一篇:Excel自動對數字列進行排序
下一篇:Python回圈不停地繼續
