簡體   English   中英

如何使setTimeout()在for循環中工作?

[英]how to make setTimeout() work as it looks like in for-loop?

如何使setTimeout()在for循環中工作? 像這樣的代碼

function hello() {
    for (let index = 0; index < 3; index++) {
        setTimeout(function () {
            console.log('What\'s up!')
        }, 3000)
        console.log('Yo')
    }
}

hello()

它記錄

Yo
Yo
Yo
What's up!
What's up!
What's up!

我如何使其成為日志

Yo
What's up(after 3 sec)
Yo
What's up(after 3 sec)
Yo
What's up(after 3 sec)

謝謝你的幫助。

一種方法是這樣的:

 function hello() { for (let index = 1; index <= 3; index++) { setTimeout(function () { console.log('What\\'s up!') }, 3000 * index) setTimeout(function () { console.log('Yo') }, 3000 * (index - 1)) } } hello() 

我基本上利用了for循環索引來給每個console.log調用不同的延遲。 請注意,“ Yo”如何始終比“ Whats up”快3000 ms。

您需要Promise遞歸來進行此類操作。

承諾 (沒有異步/等待

 async function hello(index = 0) { if (index >= 3) return; index += 1; return new Promise(function(resolve){ setTimeout(function(){ console.log('What\\'s up!'); resolve(); }, 3000); console.log('Yo'); }).then(hello.bind(null, index)); } hello() 

承諾 (使用async / await

 async function hello() { for (let index = 0; index < 3; index++) { await Promise.all([ new Promise(function(resolve){ setTimeout(function(){ console.log('What\\'s up!'); resolve(); }, 3000); }), console.log('Yo') ]); } } hello() 

遞歸

 function hello(index = 0) { if (index >= 3) return; setTimeout(function(){ console.log('What\\'s up!'); hello(index); }, 3000); console.log('Yo'); index++; } hello() 

PS :以上代碼假定您使用ES2017及更高版本。

即使您將等待時間設為0,setTimeout()也不會給您想要的結果。 可以將console.log都放入setTimeout()或刪除setTimeout()。

您需要這樣的東西:

 const times = 3; var n = 0; function logYo(){ console.log('Yo'); logWhatsUp(); } function logWhatsUp(){ setTimeout(() => { console.log('Whats Up'); n++; if(n < times) logYo(); }, 3000); } logYo(); 

您可以只創建一個使用setTimeout()執行自身的函數,但必須將全局函數合並為計數器。

let counter = 0;
function hello(n){
    console.log("Yo");
    console.log("What's up?);
    counter++;
    if(counter > n){
        setTimeout(hello, 3000);
    }
}

如果要每3秒輸出另一對日志,請使用async / awaitpromises查看以下代碼段:

 async function hello() { for (let index = 0; index < 3; index++) { console.log('Yo'); await new Promise(resolve => { setTimeout(function () { console.log('What\\'s up!'); resolve(); }, 3000); }); } } hello(); 

確保您檢查出例如caniuse,以檢查您要支持的瀏覽器是否支持async / awaitPromise

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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