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

JS的事件循环机制 #12

Open
ZYuMing opened this issue Jan 12, 2019 · 0 comments
Open

JS的事件循环机制 #12

ZYuMing opened this issue Jan 12, 2019 · 0 comments

Comments

@ZYuMing
Copy link
Owner

ZYuMing commented Jan 12, 2019

前言

先来个🌰,执行下面代码,输出的顺序是怎样的?

console.log('script start')
setTimeout(function() {
  console.log('setTimeout')
}, 0)
Promise.resolve().then(function() {
  console.log('promise1')
}).then(function() {
  console.log('promise2')
});

console.log('script end')

正确答案是script start, script end, promise1, promise2, setTimeout

要想弄不明白为什么是这顺序,你需要知道事件循环(Event Loop)是如何处理微任务(Micro Task)跟宏任务(Macro Task)

事件循环(Event Loop)

事件循环就是个循环,其不断检查是否有有事件待处理,如果有就处理该事件。如果没有则进入下一个循环。在每个循环中通过观察者模式来说判断是否有事件需要处理。事件的顺序决定了js代码的执行顺序。

任务

同步任务 即可以立即执行的任务,如console.log打印一条日志、声明一个变量或者执行一次加法等
异步任务 不会立即执行的事件任务,包括宏任务和微任务

宏任务(Macro Task)

不会导致页面渲染的阻塞

script(全局任务), setTimeout, setInterval, setImmediate, I/O, UI rendering

微任务(Micro Task)

会影响页面渲染

process.nextTick, promise.then(), object.observe, MutationObserver

执行顺序

回到实例

console.log('script start')
setTimeout(function() {
  console.log('setTimeout')
}, 0)
Promise.resolve().then(function() {
  console.log('promise1')
}).then(function() {
  console.log('promise2')
});

console.log('script end')
  1. 代码运行到console.log('script end')时
macro queue: ['Run script', 'setTimeout callback']
micro queue: ['Promise then']
stack: ['script']
log: ['script start', 'script end']
  1. 运行到console.log('promise2')时
macro queue: ['Run script', 'setTimeout callback']
micro queue: ['Promise then']
stack: ['Promise callbak']
log: ['script start', 'script end','promise1', 'promise2']
  1. 运行到console.log('setTimeout')时
macro queue: ['setTimeout callback']
micro queue: []
stack: ['setTimeout callback']
log: ['script start', 'script end','promise1', 'promise2', 'setTimeout']
  1. 结束
macro queue: []
micro queue: []
stack: []
log: ['script start', 'script end','promise1', 'promise2', 'setTimeout']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant