[英]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。
承诺 (没有异步/等待 )
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 / await和promises查看以下代码段:
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 / await和Promise 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.