宏任务和微任务相关概念和例子

javascript是一门单线程语言,所有任务需要排队,前一个任务结束,才会执行后一个任务。如果上一个任务的执行过程耗时很长,下一个任务就不得不等待很长的时间,这时设计者就把任务设成了同步任务和异步任务。同步任务在主线程上是一个个执行,而异步任务则会进入任务队列(task queue),只有在所有同步任务执行完,异步任务才会被执行。

异步任务有:setTimeout、setlnterval、DOM事件、Promise、Ajax;

任务队列

根据规范,事件循环是通过任务队列的机制来进行协调的。一个 Event Loop 中,可以有一个或者多个任务队列(task queue),一个任务队列便是一系列有序任务(task)的集合;每个任务都有一个任务源(task source),源自同一个任务源的 task 必须放到同一个任务队列,从不同源来的则被添加到不同队列。setTimeout/Promise 等API便是任务源,而进入任务队列的是他们指定的具体执行任务。

在事件循环中,每进行一次循环操作称为 tick,每一次 tick 的任务处理模型是比较复杂的,但关键步骤如下:

  • 在此次 tick 中选择最先进入队列的任务(oldest task),如果有则执行(一次)
  • 检查是否存在 Microtasks,如果存在则不停地执行,直至清空 Microtasks Queue
  • 更新 render
  • 主线程重复执行上述步骤

在上诉tick的基础上需要了解几点:

  • JS分为同步任务和异步任务
  • 同步任务都在主线程上执行,形成一个执行栈
  • 主线程之外,事件触发线程管理着一个任务队列,只要异步任务有了运行结果,就在任务队列之中放置一个事件。
  • 一旦执行栈中的所有同步任务执行完毕(此时JS引擎空闲),系统就会读取任务队列,将可运行的异步任务添加到可执行栈中,开始执行。
    在这里插入图片描述

宏任务

(macro)task,可以理解是每次执行栈执行的代码就是一个宏任务(包括每次从事件队列中获取一个事件回调并放到执行栈中执行)。

浏览器为了能够使得JS内部(macro)task与DOM任务能够有序的执行,会在一个(macro)task执行结束后,在下一个(macro)task 执行开始前,对页面进行重新渲染,流程如下:

(macro)task->渲染->(macro)task->…

宏任务包含:

script(整体代码)
setTimeout
setInterval
I/O
UI交互事件
postMessage
MessageChannel
setImmediate(Node.js 环境)

微任务

microtask,可以理解是在当前 task 执行结束后立即执行的任务。也就是说,在当前task任务后,下一个task之前,在渲染之前。

所以它的响应速度相比setTimeout(setTimeout是task)会更快,因为无需等渲染。也就是说,在某一个macrotask执行完后,就会将在它执行期间产生的所有microtask都执行完毕(在渲染前)。
微任务包含:

Promise.then
Object.observe
MutaionObserver
process.nextTick(Node.js 环境)

运行机制

在事件循环中,每进行一次循环操作称为 tick,每一次 tick 的任务处理模型是比较复杂的,但关键步骤如下:

  • 执行一个宏任务(栈中没有就从事件队列中获取)
  • 执行过程中如果遇到微任务,就将它添加到微任务的任务队列中
  • 宏任务执行完毕后,立即执行当前微任务队列中的所有微任务(依次执行)
  • 当前宏任务执行完毕,开始检查渲染,然后GUI线程接管渲染
  • 渲染完毕后,JS线程继续接管,开始下一个宏任务(从事件队列中获取)

如图:
在这里插入图片描述宏任务->微任务->页面渲染->宏任务

简单实例分析

例子1:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        setTimeout(function () {
            new Promise(function (resolve, reject) {
                console.log('异步宏任务promise');
                resolve();
            }).then(function () {
                console.log('异步微任务then')
            })
            console.log('异步宏任务');
        }, 0)
        new Promise(function (resolve, reject) {
            console.log('同步宏任务promise');
            resolve();
        }).then(function () {
            console.log('同步微任务then')
        })
        console.log('同步宏任务')
    </script>
</body>

</html>

输出结果:

同步宏任务promise
同步宏任务
同步微任务then
异步宏任务promise
异步宏任务
异步微任务then

分析:setTimeout是异步任务,虽然他在0秒后执行但仍排在队列的后面,因此其中的代码全部靠后执行;new Promise是同步任务同时也是主任务,因此第一行先打印’同步宏任务promise’,then是微任务所以靠后执行,先执行第28行代码,之后再执行第26行的then语句,因此第二行输出为’同步宏任务’,第三行为’同步微任务then’;接下来执行setTimeout中的语句,then因为是微任务所以在第20行执行完成后再执行。

例子2:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        console.log('1');//
        setTimeout(function () {
            console.log('2');//
            new Promise(function (resolve) {
                console.log('3');//
                resolve();
            }).then(function () {
                console.log('4');//
            })
        }, 0);
        new Promise(function (resolve) {
            console.log('5');//
            resolve();
        }).then(function () {
            console.log('6');//
        });
        setTimeout(function () {
            console.log('7');//
            new Promise(function (resolve) {
                console.log('8');//
                resolve();
            }).then(function () {
                console.log('9');//
            });
        })
        console.log('10');//
        // 1 5 10 6 2 3 4 7 8 9
    </script>
</body>

</html>

输出结果:1 5 10 6 2 3 4 7 8 9

例子3(async、await、promise):

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        console.log('1');
        async function async1() {
            console.log('2');
            await async2();
            console.log('3');
        }
        async function async2() {
            console.log('4');
        }
        //调用async1
        async1();
        setTimeout(function () {
            console.log('5');
            new Promise(function (resolve) {
                console.log('6');
                resolve();
            }).then(function () {
                console.log('7');
            });
        }, 0);
        new Promise(function (resolve, reject) {
            console.log('8');
            resolve();
        }).then(function () {
            console.log('9');
        })
        setTimeout(function () {
            console.log('10');
            new Promise(function (resolve) {
                console.log('11');
                resolve();
            }).then(function () {
                console.log('12');
            });
        }, 0);
        console.log('13');
        //1 2 4 8 13 3 9 5 6 7 10 11 12
    </script>
</body>

</html>

输出结果:1 2 4 8 13 3 9 5 6 7 10 11 12

如果本文对你有帮助,请点个赞吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值