TA

TA

Event Loop

Preface#

Event Loop is a mechanism in browsers or Node that solves the problem of JavaScript's single-threaded runtime not blocking, which is the principle behind asynchronous operations that we often use.

Event Loop#

In JavaScript, tasks are divided into two types: macro tasks (also known as tasks) and micro tasks.

Macro Tasks#

Script code, setTimeout, setInterval, setImmediate (not supported by browsers, only supported by IE10, see MDN for details), I/O, UI Rendering.

Micro Tasks#

Process.nextTick (Node-specific), Promise, Object.observe (deprecated), MutationObserver (see here for specific usage).

Event Loop in Browsers#

JavaScript has a main thread and a call stack, where all tasks are placed in the call stack waiting for the main thread to execute.

JS Call Stack#

The JS call stack follows the rule of last in, first out. When a function is executed, it is added to the top of the stack. After the execution stack is completed, it is removed from the top of the stack until the stack is empty.

Synchronous Tasks and Asynchronous Tasks#

JavaScript's single-threaded tasks are divided into synchronous tasks and asynchronous tasks. Synchronous tasks are executed in the call stack in order, while asynchronous tasks register their callback functions in the task queue and wait for the main thread to be idle (when the call stack is empty) after the asynchronous tasks have results. The tasks are then read into the stack and wait for the main thread to execute. The task queue, also known as the Task Queue, is a first-in, first-out data structure.

Event Loop Process Model#

Select the task queue to be executed, select the task that entered the task queue first, and if the task queue is empty (null), jump to the execution steps of micro tasks.
Set the task in the event loop as the selected task.
Execute the task.
Set the currently running task in the event loop as null.
Remove the completed task from the task queue.
Microtask steps: enter the microtask checkpoint.
Update the UI rendering.
Return to the first step.

When entering the microtask checkpoint, the user agent performs the following steps:#

Set the microtask checkpoint flag to true.
When the event loop microtask execution is not empty: select the microtask in the microtask queue that entered first, set the event loop microtask as the selected microtask, run the microtask, set the completed microtask as null, and remove the microtask from the microtask queue.
Clean up IndexDB transactions.
Set the flag for entering the microtask checkpoint to false.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.