[英]Javascript Asynchronous with setTimeout(…, 0)
I wanted to have a better understanding of how the event loop and asynchronous code works in Javascript. 我想更好地了解事件循环和异步代码在Javascript中的工作方式。 There is a ton of resources online but I could not find an answer to my question
在线上有大量资源,但我找不到我的问题的答案
Everyday I mostly use callbacks, promises, async/awaits, but at the end I am simply relying on already asynchronous methods. 每天我大多数时候都使用回调,promise,异步/唤醒,但是最后我只是依靠已经异步的方法。
Therefore I wanted to know how it works, creating an async function from scratch, and deal with blocking code (or should I say slow code, that is not an HttpRequest or anything that is already provided to us). 因此,我想知道它是如何工作的,从头开始创建一个异步函数,并处理阻塞代码(或者我应该说慢速代码,它不是HttpRequest或已经提供给我们的任何东西)。
For example taking while loop with a very high condition to stop it, should take a second to finish. 例如,以很高的条件进行while循环来停止它,应该花一秒钟完成。 And this is what I decided to implement for my tests.
这就是我决定为测试实施的内容。
After my research, I could read that one way of making my code asynchronous, would be to use setTimeout
with a 0ms delay (placing a message in the event queue, that will be executed after the next tick) 经过研究,我可以读到使代码异步的一种方法是使用
setTimeout
,延迟为0ms(将消息放入事件队列中,该消息将在下一个滴答之后执行)
function longOperation(cb) {
setTimeout(function() {
var i = 0;
while (i != 1000000000) { i++; }
cb();
}, 0);
}
longOperation(() => {
console.log('callback finished');
})
console.log('start');
My question is: 我的问题是:
When my code is finally going to be executed, why isn't it blocking anymore ? 当我的代码最终将要执行时,为什么它不再阻塞了? What is the difference between executing it normally, and placing a message that the event loop will pick to push it to the call stack ?
正常执行它和放置事件循环将其推送到调用堆栈的消息之间有什么区别?
The following video shows how the event loop handles a setTimeout
with 0 delay. 以下视频显示事件循环如何处理延迟为0的
setTimeout
。
JavaScript Event loop with setTimeout 0 setTimeout为0的JavaScript事件循环
However, the code executed is a simple console log. 但是,执行的代码是一个简单的控制台日志。 In my example, this is a "long" operation...
在我的示例中,这是一个“长时间”操作...
while
loop and its callback). while
循环及其回调)。 During both of these code execution phases, no other JavaScript user code will run. 在这两个代码执行阶段中,将不会运行其他JavaScript用户代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.