why

We all know that Js is single-threaded, but some time-consuming operations can cause process blocking problems. To solve this problem, Js has two execution modes for tasks: Synchronous and Asynchronous.

explain

In asynchronous mode, you can create asynchronous tasks into macro tasks and micro tasks. In the ES6 specification, macrotasks are called tasks and microtasks are called Jobs. Macro tasks are initiated by the host (browser, Node), while microtasks are initiated by JS itself.

Several ways to create macro tasks and micro tasks

MacroTasks Microtasks
setTimeout RequestAnimationFrame (controversial)
setInterval MutationObserver (Browser environment)
MessageChannel Promise.[ then/catch/finally ]
I/O, event queue Process.nexttick (Node environment)
SetImmediate (Node environment) queueMicrotask
Script (whole block of code)

Understanding a script is a macro task

In fact, if two script blocks exist at the same time, the synchronization code in the first script block will be executed first. If a microtask is created and entered into the microtask queue during this process, after the execution of the first script synchronization code, the microtask queue will be emptied first. Start the execution of the second script block. So this should make sense why a script is a macro task.