JavaScript 執行機制領悟

以前只知道事件隊列,不知道,任務也分:宏仁務、微任務

宏任務:包括整體代碼script,setTimeout,setInterval 

微任務:Promise的then,catch,process.nextTick

不同類型的任務會進入對應的Event Queue,比如setTimeoutsetInterval會進入相同的Event Queue.

執行一次宏仁務,再執行所有的微任務;再執行一次宏仁務,再執行所有的微任務;一直循環直到全部執行完畢

console.log('1');

setTimeout(function() {
    console.log('2');
    process.nextTick(function() {
        console.log('3');
    })
    new Promise(function(resolve) {
        console.log('4');
        resolve();
    }).then(function() {
        console.log('5')
    })
})
process.nextTick(function() {
    console.log('6');
})
new Promise(function(resolve) {
    console.log('7');
    resolve();
}).then(function() {
    console.log('8')
})

setTimeout(function() {
    console.log('9');
    process.nextTick(function() {
        console.log('10');
    })
    new Promise(function(resolve) {
        console.log('11');
        resolve();
    }).then(function() {
        console.log('12')
    })
})

答案:1 7 6 8 2 4 3 5 9 11 10 12

 

學習來源 一篇大神的博客:https://juejin.im/post/59e85eebf265da430d571f89

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章