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('代码执行结束');

输出结果:

3.

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

输出结果:

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)

输出结果:

除了广义的同步任务和异步任务,我们对任务有更精细的定义:

  • macro-task(宏任务):包括整体代码script,setTimeout,setInterval
  • micro-task(微任务):Promise,process.nextTick

 

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')
        })
    })

输出结果:

参考链接:https://juejin.im/post/59e85eebf265da430d571f89

原文地址:https://www.cnblogs.com/xutongbao/p/11915690.html