(flag)每日面試題-JavaScript 執行機制,宏任務,微任務


JavaScript 執行機制,宏任務,微任務
1.js是一門單線程語言 瀏覽器是多線程的
2.同步進入主線程
3.異步進入Event Table並注冊函數,當指定的事情完成時,Event Table會將這個函數移入到Event Queue中,主線程任務執行完畢之后 會去Event Queue讀取相應的函數 上面這個過程會不斷的重復,也就是Event Loop(事件循環)
事件循環:scrip是一個宏觀任務 宏觀任務結束之后 才會去執行下一個宏觀任務,其中如果有微觀任務會去執行所有的微觀任務,執行完畢所有的微觀任務之后,執行下一個宏觀任務
宏觀任務
macro-task(宏任務):包括整體代碼script,setTimeout,setInterval
微觀任務
micro-task(微任務):Promise,process.nextTick(process.nextTick()的意思就是定義出一個動作,並且讓這個動作在下一個事件輪詢的時間點上執行)
如下代碼解析:

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.第一個宏觀任務script 作為整體進入主線程 遇到console.log('1') 輸出1
2.遇到setTimeout,宏觀任務(現在第一個宏觀任務script還沒有執行完畢 會分配到宏觀任務中 暫時還不會執行)
3.遇到下面的process.nextTick 分配到微觀任務中
4.遇到Promise,new Promise直接執行,輸出7。then被分發到微任務Event Queue中 5.此時的微觀任務表中:process.nextTick,Promise.then 則執行結果為 6 8
第一個宏觀任務 執行結果 : 1 7 6 8
第二個宏觀任務:
1.第二個宏觀任務是第一個setTimeout
2.跟script的執行順序是一樣的 碰到console.log('2') 執行2 process.nextTick會分配到微觀任務 Promise會立即執行 然后.then分配到微觀任務
輸出結果:2 4 3 5
第三個宏觀任務:
第三個宏觀任務就是第二個setTimeout 和第二個宏觀任務執行順序一樣
輸出結果 9 11 10 12

練習題1:

// 宏觀任務  setTimeout 
// 微觀任務    async1 .then .then

    console.log('script start')//1
    async function async1() { //async 語法糖 async2()執行完畢 才執行下面 會加入在微觀任務里面
        await async2()
        console.log('async1 end') //5
    }
    async function async2() {
        console.log('async2 end') //2
    }
    async1()

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

    new Promise(resolve => {
        console.log('promise') //3
        resolve()
    }).then(function () {
        console.log('promise1') //6
    }).then(function () {
        console.log('promise2') //7
    })

    console.log('script end') //4

練習題2:

  async function async1() {
        console.log(1);
        const result = await async2();
        console.log(3);
    }

    async function async2() {
        console.log(2);
    }

    Promise.resolve().then(() => {
        console.log(4);
    });

    setTimeout(() => {
        console.log(5);
    });

    async1();
    console.log(6);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM