JavaScript event loop mechanism (Event Loop) Brief

Single-threaded JavaScript

JavaScript is a scripting language browser. Its main role is to interact with the client. Initially designed from the beginning it is single-threaded. Because it is mainly operating DOM. If designed as a multi-threaded, suppose a thread in a DOM node operation, delete a thread again in this DOM node. This time the browser will not be able to determine which thread-based, this complex scenario has greatly increased the difficulty of the language. So JavaScript is born from a single-threaded. It is also one of the most important features.

Task Queue

Because JavaScript is single-threaded, so all tasks can only be one waiting to be executed. If a task has been occupied by the CPU, let me say. But sometimes IO (input and output devices) takes a long time, while the CPU is idle. So in order to effectively utilize CPU. IO devices can be time-consuming tasks pending, perform the latter task. Wait until IO device returns the result, then come back to the implementation of pending tasks. Task queue is a FIFO structure, the top surface of events, preferential access to the main thread is executed.

Operating mechanism

  1. All tasks in the main thread of execution, execution stack formation.
  2. Outside the main thread, there is a task queue. The system asynchronous tasks in the task queue.
  3. Wait until the main thread of task execution is completed, the system will read task task queue.
  4. Asynchronous tasks waiting for the end of the state, will enter the execution stack from the task queue, resume execution.
  5. Repeat the above steps main thread.

Event callbacks

In addition to the common IO device, user interaction (click, slide, touch, etc.) will be added to the task queue, waiting for the main thread to read. IO device to complete a task, is to add an event in the "Task Queue" in. It indicates that the associated tasks can enter the execution stack. The main thread reads the task queue, which is read callback events there.
The callback function is to be suspended task queue code. Asynchronous tasks must specify a callback function. When the asynchronous task execution stack back from the task queue, that is, when the callback function is executed.

Event cycle (Event Loop)

When the main thread running will produce heap and stack. Stack code calls the various external API. They join various events in the task queue. As long as the code is executed in the stack is completed, it will be the main thread to read "task queue", which events corresponding to the callback function in sequence. The main thread reads events from the "Task Queue" in this process is ongoing cycle. So called event loop mechanism.

Published 263 original articles · won praise 2448 · Views 170,000 +

Guess you like

Origin blog.csdn.net/weixin_44135121/article/details/104400084