Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Event Loop 理解总结 #131

Open
hoperyy opened this issue Feb 8, 2019 · 0 comments
Open

Event Loop 理解总结 #131

hoperyy opened this issue Feb 8, 2019 · 0 comments

Comments

@hoperyy
Copy link
Owner

hoperyy commented Feb 8, 2019

参考资料

http://web.jobbole.com/95613/

浏览器和 Node 的执行顺序

  1. 先清空调用栈
  2. 清空微任务
  3. 执行 Event Loop

这样才会出现:

setTimeout(function timeout () {  
         console.log('timeout');
},0);
setImmediate(function immediate () { 
         console.log('immediate');
});

对于以上代码来说,setTimeout 可能执行在前,也可能执行在后。

首先 setTimeout(fn, 0) === setTimeout(fn, 1),这是由源码决定的。

进入事件循环也是需要成本的,如果在准备时候花费了大于 1ms 的时间,那么在 timer 阶段就会直接执行 setTimeout 回调。

如果准备时间花费小于 1ms,那么就是 setImmediate 回调先执行了。

浏览器

image

Node

image

image

右图需要纠正:

Node11 以前,是每个阶段的函数执行完,再清理微任务;

Node11 后,是每个阶段的 1 个宏任务执行完就清理微任务。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant