宏任務(wù): setTimeout 、 setInterval 、 DOM事件、Ajax請求
DOM渲染
微任務(wù): Promise、async/await
const set1 = setTimeout(function(){
? ? console.log('set1')
? ? setTimeout(function(){
? ? ? ? console.log('set3')
? ? })
? ? new Promise(function(resolve){
? ? ? ? resolve()
? ? }).then(function(){
? ? ? ? new Promise(function(resolve){
? ? ? ? ? ? resolve()
? ? ? ? }).then(function(){
? ? ? ? ? ? console.log('then5')
? ? ? ? })
? ? ? ? console.log('then6')
? ? })
})
new Promise(function(resolve){
? ? console.log('pr1');
? ? resolve()
}).then(function(){
? ? console.log('then1')
? ? new Promise(function(resolve){
? ? ? ? resolve()
? ? }).then(function(){
? ? ? ? new Promise(function(resolve){
? ? ? ? ? ? resolve()
? ? ? ? }).then(function(){
? ? ? ? ? ? console.log('then4')
? ? ? ? })
? ? ? ? console.log('then2')
? ? })
})
const set2 = setTimeout(function(){
? ? console.log('set2')
})
console.log(2)
上面代碼執(zhí)行結(jié)果:
pr1
?2
then1
then2
then4
set1
then6
then5
set2
set3
首先同步代碼打印結(jié)果 --- pr1 、1 (new Promise是同步的,resolve、reject更改狀態(tài),如果有then函數(shù)則會丟入微任務(wù)隊(duì)列)
set1、set2 為setTimeout 函數(shù),會丟入宏任務(wù)隊(duì)列
當(dāng)同步代碼執(zhí)行完,先執(zhí)行微任務(wù)隊(duì)列的任務(wù),
打印 --- then1 ,同時(shí)又丟了一個(gè) then函數(shù)到 微任務(wù),@1 則繼續(xù)執(zhí)行 微任務(wù)(因?yàn)橐欢〞葓?zhí)行完微任務(wù)才會執(zhí)行宏任務(wù))
打印 --- then2, 重復(fù)上步驟
打印? --- then4
到此,微任務(wù)隊(duì)列清空,接下來按順序執(zhí)行宏任務(wù)
打印 --- set1
此時(shí)又丟了一個(gè) 微任務(wù)到隊(duì)列 和一個(gè) 宏任務(wù)到隊(duì)列
根據(jù)打印結(jié)果,先打印的是 then6? ?then5 , 而不是 set2 , 這里我理解的是 每次執(zhí)行完一個(gè) 異步隊(duì)列任務(wù),都會先詢問還有 微任務(wù)沒,沒有再詢問還有宏任務(wù)沒(@1 處 也是因?yàn)槿绱耍?/p>
未完待續(xù)......? ??
執(zhí)行順序: 微任務(wù) > DOM渲染 > 宏任務(wù)