[英]How to fix: setTimeout function within a forEach function not following correct timeout
我正在嘗試讓消息顯示在我的網站上,每 3 秒后顯示一次。 我通過一個帶有 forEach 函數的數組(包含消息)將它們放入 setTimeout 函數中,但它只是在 3 秒后顯示最后一條消息,而不是在 3 秒后顯示所有消息。
我試過調試,這里奇怪的部分是它確實在調試中工作,只是沒有它。
const travelIntro = $text => {
const arrMessages = ['You are travelling through empty space...', 'You wake up with only 5% oxygen left barely breathing', 'All of the sudden your ship starts up'];
arrMessages.forEach(message => {
setTimeout(function () {
$text.innerHTML = message;
}, 3000);
});
}
所以我希望它在 3 秒后在每條消息之間切換,而不僅僅是顯示數組中的最后一條。
您肯定需要了解 Javascript 中異步的本質
forEach 循環實際上會運行得非常快,並且對於每條消息,它都會立即開始超時。 每個超時將在啟動后 3000 毫秒觸發。 所以它們都在 3000 毫秒后一個接一個地觸發。
為了使第二個在第一個在 3000 毫秒后觸發 3000 毫秒后觸發,您可能需要建立某種手動循環
const arrMessages = ['You are travelling through empty space...', 'You wake up with only 5% oxygen left barely breathing', 'All of the sudden your ship starts up'];
function doLoop(i) {
let message = arrMessages[i];
setTimeout(function () {
$text.innerHTML = message;
if(i < arrMessages.length-1)
doLoop(i+1);
}, 3000);
}
doLoop(0);
我認為您正在尋找setInterval
,然后在它返回 undefined 時將其清除。 在這里小提琴: https : //jsfiddle.net/xukL1w0a/
const arrMessages = ['You are travelling through empty space...', 'You wake up with only 5% oxygen left barely breathing', 'All of the sudden your ship starts up'];
let messages = setInterval(function () {
message = arrMessages.shift();
if (message === undefined) {
clearInterval(messages);
return;
}
console.log(message)
},3000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.