javascript
Javascript is a single-threaded language.
Javascript event loop
The execution mechanism of javascript is the Event Loop.
1. Js tasks
1.1. Generalized: It can be divided into synchronous tasks and asynchronous tasks.
1.2. Segmentation: macro tasks and micro tasks.
- Macro-task: includes the entire code script, setTimeout, and setInterval
- Micro-task: Promise, process.nexttick
2. Js execution mechanism
Event loop
1. Synchronous and asynchronous tasks enter different execution “places” respectively. Synchronous tasks enter the main thread and asynchronous tasks enter the Event Table and register functions.
2. The Event Table moves this function to the Event Queue when the specified Event completes.
3. If the tasks in the main thread are empty after execution, the Event Queue will read the corresponding function and enter the main thread for execution.
4. This process is repeated over and over again, known as an Event Loop.
3, event loop, macro task, micro task diagram
1. The overall code script enters the main thread as the first macro task; If a macro task is encountered during the execution of the main thread task, its callback function is distributed to the macro task Event Queue. If a microtask is encountered, its callback function is distributed to the microtask Event Queue. The main thread completes, there are microtasks, execute all the microtasks in the Event Queue; No microtask, start a new macro task. The first cycle of events is officially over.
2. The second round of the Event loop starts from the macro task Event Queue and enters the main thread as a new macro task.
The original reference: mp.weixin.qq.com/s/MELXPrwLY…