简体   繁体   English

如何在 JavaScript 中依次执行 Console.log 和 setTimeout

[英]How to execute Console.log and setTimeout sequentially in JavaScript

(function() {
    console.log(1); 
    setTimeout(function(){console.log(2)}, 1000); 
    setTimeout(function(){console.log(3)}, 0); 
    console.log(4);
})();

Hello All,大家好,

When I run the above code, it produces the following output: 1,4,2,3当我运行上面的代码时,它会产生以下 output: 1,4,2,3

So, instead of producing 1,4,2,3 I want the output to be 1,2,3,4 but by using setTimeout() method only.因此,我希望 output 为 1,2,3,4 而不是生成 1,4,2,3,但仅使用 setTimeout() 方法。

Can anyone please help me out on how to produce 1,2,3,4 by having setTimeout() method and making modifications to it.任何人都可以通过使用 setTimeout() 方法并对其进行修改来帮助我了解如何生成 1、2、3、4。

To simplify things.. wrap the setTimeout with a Promise - that will give you the ability to also use async and await keywords and simplify your logic为了简化事情.. 用Promise包装setTimeout - 这将使您能够使用asyncawait关键字并简化您的逻辑

 (async function() { function sleep(interval) { return new Promise(resolve => { setTimeout(resolve, interval) }) } console.log(1) await sleep(1000) console.log(2) await sleep(1000) console.log(3) await sleep(1000) console.log(4) })();

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

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