微任務(wù)和宏任務(wù)執(zhí)行順序

宏任務(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ù)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容