简体   繁体   English

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

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

how to make setTimeout() work as it looks like in for-loop? 如何使setTimeout()在for循环中工作? like this code 像这样的代码

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

hello()

it logs 它记录

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

How can I make it logs 我如何使其成为日志

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

Thanks for your help. 谢谢你的帮助。

One way to do it is this: 一种方法是这样的:

 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() 

I basically made use of the for loop index to give each console.log call a different delay. 我基本上利用了for循环索引来给每个console.log调用不同的延迟。 Note how "Yo" is always 3000 ms ahead of "What's up". 请注意,“ Yo”如何始终比“ Whats up”快3000 ms。

You need either Promise or recursion for operations like this. 您需要Promise递归来进行此类操作。

Promise (without async/await ) 承诺 (没有异步/等待

 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() 

Promise (with async/await ) 承诺 (使用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() 

Recursion 递归

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

PS : Codes above assume you use ES2017 and above. PS :以上代码假定您使用ES2017及更高版本。

setTimeout() will not give you desired result even if you put 0 waiting time. 即使您将等待时间设为0,setTimeout()也不会给您想要的结果。 Either put both the console.log in setTimeout() or remove setTimeout(). 可以将console.log都放入setTimeout()或删除setTimeout()。

You need something like this: 您需要这样的东西:

 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(); 

You can just make a function which executes itself with setTimeout() but you would have to incorporate a global function as a counter. 您可以只创建一个使用setTimeout()执行自身的函数,但必须将全局函数合并为计数器。

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

If you want to output every 3 seconds another pair of logs, take a look at the following snippet using async/await and promises : 如果要每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(); 

Make sure you check out for example caniuse to check whether the browsers you want to support is supporting async/await and Promise though. 确保您检查出例如caniuse,以检查您要支持的浏览器是否支持async / awaitPromise

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM