1.什麼是事件循環?
JavaScript爲單線程執行的,因此是從上到下依次執行,js分爲兩個任務,宏任務和微任務promise
首先執行宏任務(第一次就是執行全部的同步代碼),再執行全部的微任務,執行完畢以後再次執行post
宏任務,執行完畢再次執行全部的微任務,也就是:spa
宏任務 --> 微任務 --> 宏任務 --> 微任務線程
2.什麼是宏任務,微任務?
宏任務:code
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)server
再執行全部的微任務 console.log(3)blog
再一次從上到下執行全部的微任務:console.log(1) console.log(5)事件
因此正確答案是 2 4 3 1 5ip
咱們再加大難度
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'
)
})
|
解讀:ci
咱們先執行同步代碼: start
微任務:promise 1 , promise 2
宏任務: setTimeout 1
微任務:promise 3, promise 4
宏任務:setTimeout 2 ,
微任務:promise 5,promise 6
正確答案