事件循环
浏览器
console.log(1)
setTimeout(() => {
console.log(2)
new Promise(resolve => {
console.log(4)
resolve()
}).then(() => {
console.log(5)
})
})
new Promise(resolve => {
console.log(7)
resolve()
}).then(() => {
console.log(8)
})
setTimeout(() => {
console.log(9)
new Promise(resolve => {
console.log(11)
resolve()
}).then(() => {
console.log(12)
})
})
// 1 7 8 2 4 5 9 11 12
- queue可以看做一种数据结构,用以存储需要执行的函数
- timer类型的API(setTimeout/setInterval)注册的函数,等到期后进入task队列(这里不详细展开timer的运行机制)
- 其余API注册函数直接进入自身对应的task/microtask队列
- Event Loop执行一次,从task队列中拉出一个task执行
- Event Loop继续检查microtask队列是否为空,依次执行直至清空队列
node事件循环
- idle观察者(nextTick) > I/O观察者(setTimeout,setInterval) > check观察者(setImmediate)
Macrotask
- setTimeout
- setInterval
- setImmediate
Microtask
本文标题:事件循环
本文链接:https://www.haomeiwen.com/subject/xfqajqtx.html
网友评论