[Javascript] Macro and Micro tasks

Macro:

refer to webapis, setTimeout, setInterval

Micro:

refer to Promise based api

Execution order

Sync Task > Micro Task > Macro Task

Example:

const l = console.log

const macro = v => setTimeout(() => l(v))
const micro = v => Promise.resolve().then(() => l(v))

l(1)
macro(2)
micro(3)
l(4)

So, you can think about the output.

..

..

..

..

..

..

// 1 4 3 2

So run all the sync tasks first, 

therefore // 1 4

Then follw by micro task: // 1 4 3

Then follow by macro task: // 1 4 3 2

原文地址:https://www.cnblogs.com/Answer1215/p/12788599.html