Event Loop

JS tasks are divided into synchronous tasks and asynchronous tasks

Synchronization task: a task that is queued to be executed on the main thread can be executed only after the previous task is completed

Asynchronous task: A task that does not enter the main thread but enters the Task queue. The task queue notifies the main thread that an asynchronous task is ready to execute. (Mouse clicks, keyboard events, HTTPQ requests, setTimeOut)

Specific execution process:

  1. All synchronization tasks are executed on the main thread, forming an execution stack
  2. In addition to the main thread, there is a “task queue”. Whenever an asynchronous task has a result, an event is placed in the “task queue”.
  3. Once all synchronization tasks in the execution stack are completed, the system reads the task queue to see what events are in it. Those corresponding asynchronous tasks then end the wait state, enter the execution stack, and start executing.
  4. The main thread repeats step 3 above.

The main thread reads events from the “task queue” in a continuous Loop, so the whole operation mechanism is also called an Event Loop.

Whether it’ssetTimeout/setIntervalandXHR/fetchThe code, as it executes, is itself a synchronous task, and its callback function is an asynchronous task, and it enters the task queue

Macro task, micro task

Macro task

We can think of the code executed on each stack as a macro task (including fetching one event callback from the event queue and placing it on the execution stack at a time), and each macro task will be executed from start to finish and nothing else will be done

Micro tasks

Microtasks only come from our code. They are typically created by promise: the execution of a.then/catch/finally handler becomes a microtask. Microtasks are also used “behind the scenes” of await, as it is another form of promise processing

  • Perform a macro task (fetch from event queue if not in stack)

  • If a microtask is encountered during execution, it is added to the task queue of the microtask

  • Execute all microtasks in the current microtask queue immediately after the macro task is executed (in sequence)

  • When the macro task completes, the render is checked, and the GUI thread takes over

  • After rendering, the JS thread takes over and starts the next macro task (fetched from the event queue)

reference

“Front-end advancement” from multi-threading to Event Loop comprehensive combing

More on the Event Loop

Event loops: microtasks and macro tasks