1.什么是事件循环?
JavaScript为单线程执行的,所以是从上到下依次执行,js分为两个任务,宏任务和微任务
首先执行宏任务(第一次就是执行所有的同步代码),再执行所有的微任务,执行完毕之后再次执行
宏任务,执行完毕再次执行所有的微任务,也就是:
宏任务 --> 微任务 --> 宏任务 --> 微任务
2.什么是宏任务,微任务?
宏任务:
script(全局任务), setTimeout, setInterval, setImmediate, I/O, UI rendering.
微任务:
process.nextTick, Promise.then, Object.observer, MutationObserver.
3.案例深入解读
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
setTimeout(function(){
console.log(1)
},0)
new
Promise((resolve,reject)=>{
console.log(2)
resolve(3)
setTimeout(function(){
console.log(5)
promise.resolve
},0)
}).then((val)=>{
console.log(val)<br> })
console.log(4)
|
解读:
首先执行宏任务(同步代码) :console.log(2) console.log(4)
再执行所有的微任务 console.log(3)
再一次从上到下执行所有的微任务:console.log(1) console.log(5)
所以正确答案是 2 4 3 1 5
我们再加大难度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
console.log(
'start'
)
setTimeout(() => {
console.log(
'setTimeout 1'
)
Promise.resolve().then(() => {
console.log(
'promise 3'
)
}).then(() => {
console.log(
'promise 4'
)
}).then(() => {
setTimeout(() => {
console.log(
'setTimeout 2'
)
Promise.resolve().then(() => {
console.log(
'promise 5'
)
}).then(() => {
console.log(
'promise 6'
)
})
}, 0)
})
}, 0)
Promise.resolve().then(() => {
console.log(
'promise 1'
)
}).then(() => {
console.log(
'promise 2'
)
})
|
解读:
我们先执行同步代码: start
微任务:promise 1 , promise 2
宏任务: setTimeout 1
微任务:promise 3, promise 4
宏任务:setTimeout 2 ,
微任务:promise 5,promise 6
正确答案