天天看點

JavaScript 執行機制(宏任務和微任務)

1.

setTimeout(function() {
      console.log('1')
    });

    new Promise(function(resolve) {
      console.log('2');
      resolve();
    }).then(function() {
      console.log('3')
    });

    console.log('4');      

輸出結果:2,4,3,1

2.

setTimeout(function(){
        console.log('定時器開始啦')
    });

    new Promise(function(resolve){
        console.log('馬上執行for循環啦');
        for(var i = 0; i < 10000; i++){
            i == 99 && resolve();
        }
    }).then(function(){
        console.log('執行then函數啦')
    });

    console.log('代碼執行結束');      

輸出結果:

JavaScript 執行機制(宏任務和微任務)

3.

$.ajax({
        type: "get",
        dataType:'jsonp',
        url:'https://ipinfo.io',
        success:() => {
            console.log('發送成功!');
        }
    })
    console.log('代碼執行結束');      

輸出結果:

JavaScript 執行機制(宏任務和微任務)

4.

function sleep(delay) {
      var start = (new Date()).getTime();
      while ((new Date()).getTime() - start < delay) {
        continue;
      }
    }
    console.log(new Date)
    setTimeout(() => {
      console.log('延時并不是三秒3秒, 而是5秒')
      console.log(new Date)
    },3000)
    sleep(5000)      

輸出結果:

JavaScript 執行機制(宏任務和微任務)

除了廣義的同步任務和異步任務,我們對任務有更精細的定義:

  • macro-task(宏任務):包括整體代碼script,setTimeout,setInterval
  • micro-task(微任務):Promise,process.nextTick
JavaScript 執行機制(宏任務和微任務)

5.

console.log('1');

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

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

輸出結果:

JavaScript 執行機制(宏任務和微任務)

繼續閱讀