What is Event Loop
An Event Loop is a mechanism in a browser or Node that allows javaScript to run in a single thread without blocking, and is often used asynchronously.
Ii. Loop mechanism of Event Loop
- Synchronous and asynchronous tasks are executed in different ‘places’. All synchronous tasks are executed on the main thread, forming an execution stack. Asynchronous tasks enter the Event Table and register callback functions.
- The synchronization task is executed first, and the synchronization events are successively added to the execution stack.
- When encountering a synchronization task, push it directly onto the stack and execute it, and then pop it out of the stack after executing it.
- When the asynchronous task has running results, the Event Table will move the callback function to the Event Queue for waiting. When the synchronization task in the main thread is completed, the corresponding function will be read from the Event Queue and executed in the main thread.
- Asynchronous tasks are divided into macrotasks (e.g., script entire code, setTimeout, setInterval) and microtasks (Promise, process.nexttick).
- If the execution stack is empty, the microTask queue is checked. If the execution stack is empty, the Task (macro Task) is executed; otherwise, all the microtasks are executed at once.
- After each macro task is executed, the system checks whether the microtask queue is empty again. If there are new microtasks, all the microtasks are executed to make the microtask queue empty, and then the macro task is executed, and so on.
- The main thread repeats these steps, known as the Event Loop.