Has the JavaScript Event Loop Changed? Are There No More Macro-tasks? Let’s See What’s New
My article is open to everyone; non-member readers can click this link to read the full text.
Introduction
As is widely known, JavaScript is a single-threaded language that operates on the browser’s main rendering thread, and there is only one such thread. However, this main rendering thread handles many tasks such as rendering pages, among others.
If all code were synchronous, any piece of code that gets stuck would block the main thread, significantly impacting performance efficiency.
Therefore, browsers adopt an asynchronous approach to avoid this situation. Specifically, when certain tasks occur, such as timers, network, event listeners, etc., the main thread delegates the task to other threads for timing or listening. When the main thread has nothing to do, or when the timing or listening triggers, it adds the task to the end of the message queue to wait in line for the main thread to schedule it.
Macro-tasks and Micro-tasks
In the past version of JavaScript, asynchronous tasks were divided into macro-tasks and micro-tasks.
The JavaScript engine follows the event loop mechanism, where after completing the current macro-task, it checks the micro-task queue, executes the micro-tasks therein, and then picks up the next macro-task for execution. This process continues in a loop…