JS中的事件循環

    console.log('start');
    setTimeout(() => {
      console.log('children2');
      Promise.resolve().then(() => {
        console.log('children3');
      })
    }, 0);

    new Promise(function (resolve, reject) {
      console.log('children4');
      setTimeout(function () {
        console.log('children5');
        resolve('children6')
      }, 0)
    }).then((res) => {
      console.log('children7');
      setTimeout(() => {
        console.log(res);
      }, 0)
    })
//輸出
//start 4 2 3 5 7 6

宏任務

包括:包含執行整體的js代碼,事件回調,XHR回調,定時器(setTimeout/setInterval/setImmediate),IO操作,UI render

微任務

包括:更新應用程序狀態的任務,包括promise回調,MutationObserver,process.nextTick,Object.observe

image.png

事件循環的步驟
1.執行宏任務隊列中的一個任務
2.執行微任務隊列中的所有任務
3.UI render

setTimeout(function() {console.log('timer1')}, 0)

requestAnimationFrame(function(){
    console.log('requestAnimationFrame')
})

setTimeout(function() {console.log('timer2')}, 0)

new Promise(function executor(resolve) {
    console.log('promise 1')
    resolve()
    console.log('promise 2')
}).then(function() {
    console.log('promise then')
})

console.log('end')
//輸出1  : promise1,promise2,end,promise then,requestAnimationFrame,timer1,timer2
//輸出2  : promise1,promise2,end,promise then,timer1,timer2,requestAnimationFrame

瀏覽器只保證requestAnimationFrame的回調在重繪之前執行,沒有確定的時間,何時重繪由瀏覽器決定
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容