宏任务、微任务、vue nextTick了解一下?

2,317 阅读1分钟

先附上两篇参考资料Tasks, microtasks, queues and schedules,英语好的同学可直接移步,写的十分精彩。 Vue.$nextTick背后的Event Loop,Tasks, microtasks

阅读此文章需要了解js事件机制的预备知识。

宏任务、微任务

首先要说明的是task、macrotask指的都是宏任务、而microtask指的则是微任务。

每个宏任务之间,浏览器可能执行ui渲染。

微任务在当前宏任务执行完毕后且执行栈为空时执行,且此过程中产生的微任务也会被放至微任务队列中一起执行。(例如promise的回调就会被放至微任务队列)。

每个事件循环都有多个宏任务源。

常见的宏任务有:

Getting from a mouse click to an event callback requires scheduling a task, as does parsing HTML, and in the above example, setTimeout.

常见的微任务有:

When an algorithm requires a microtask to be queued, it must be appended to the relevant event loop's microtask queue; the task source of such a microtask is the microtask task source. 典型会产生microtask的有Promise、MutationObserver、Process.nextTick