Coding With Fun
Home Docker Django Node.js Articles FAQ

Event loop event loop


May 30, 2021 Article blog



To learn about event loop, let's start with the following 3 points

(1) js is a single thread

(2) Asynchronous is based on callback implementation

(3) Event loop is the implementation principle of asynchronous callbacks

Let's look at a picture

 Event loop event loop1

When a synchronization task is detected, it moves directly to the call stack and passed on to the browser

Call Stack - Browser

When an asynchronous task is detected, it is placed in the webAPI to wait for the queue, when the synchronization task is complete, the call stack is empty, and when the time is right for the asynchronous task to execute, the asynchronous task is moved to the callback queue

That's when the event loop goes to the callback queue, and if there's an event in the callback queue, the event loop gets him and transfers him to the call stack and then to the browser

Waiting for the queue-synchronization task to be executed, the call stack is empty, and the time has come for the asynchronous task to execute - callback queue-event loop acquisition-call stack-browser

It may be a bit abstract to say so, let's go straight to the example

 Event loop event loop2

We all know that the output answer is a, c, b specifically let's take a look

From top to bottom, the first is the console .log ('a'), which is a synchronization task, so place the call stack directly, output it to the browser, and empty the call stack

 Event loop event loop3

Then go to the timer, which is an asynchronous task

Put the wait queue WebAPI first

 Event loop event loop4

Asynchronous tasks are transferred to the callback queue when the following 3 criteria are met

(1) The synchronization task is complete

(2) Empty the call stack

(3) Asynchronous tasks can be performed when they arrive

When asynchronous task timer 3s arrives, it is time to execute, and asynchronous tasks are transferred to the callback queue

 Event loop event loop5

When the synchronization task is complete, the event loop starts working, goes back to the call queue to find the event task, finds it, and transfers it to the call stack

 Event loop event loop6

Finally, pass it on to the browser, which is the event loop implementation mechanism, and also confirms the above sentence, the principle of asynchronous callback is event loop