What is the event loop mechanism?
Before we introduce the event loop mechanism, we should first understand the following is the event loop mechanism, let’s first look at the following code execution order, the correct order is 1>3>2
Why the order above?
The reason is that the JS engine points to the code from the top down, so it will first execute the statement number 1, the JS engine will put this statement on the call stack, and then execute the code, print number 1 in the console, when the code is executed, it will remove the code from the call stack. The code will call the Web API and enter the callback queue 2 seconds later. At this time, the JS engine will remove setTimeout from the call stack and continue to execute the following code, so the serial number 1,3 will be printed on the screen first. So now the eventLoop comes on, it’s going to iterate through the CallBackQueue, and after 2 seconds the Web API is going to print out number 2 and put it in the CallBackQueue, and the eventLoop puts the contents of the CallBackQueue on the call stack, and it starts executing, The sequence number 2 is then printed on the screen, and this is the basic flow of the eventLoop.
Execution sequence diagram
What is the elicitation event loop
JS is an event loop!
What is the order of JS execution?
- JS is executed line by line from top to bottom.
- If a line of execution fails, the following code is stopped.
- Synchronous code is executed before asynchronous code is executed
The execution process of the event cycle
- Synchronous code, call stack execution directly off the stack
- Asynchronous code, put in the Web API, wait for the right time, put in the callbackQueue, wait until the call stack is empty, eventLoop starts working, polling
- Microtasks are executed earlier than macro tasks
- Microtasks fire before DOM rendering and macro tasks fire after DOM rendering
Fundamental differences between microtasks and macro tasks
- Microtasks are specified by ES6 syntax
- Macro tasks are specified by the browser
Fifth, the overall process of the event cycle
- Start by clearing the synchronization code in the Call Stack
- Execute the microtasks in the microtask queue
- Try DOM rendering
- The Event Loop is fired to repeatedly ask the callbackQueue if there are any statements to be executed. If there are any statements to be executed, the call Back is placed to continue execution
Classic case of event cycle
The resources
What is an Event Loop?
What is an Event Loop?