The event loop is a core programming concept that coordinates task execution with asynchronous event handling. Widely found in: JavaScript, Node.js, Browser runtimes, Flutter, java, Game engines and some high-performance services such as Redis and Nginx.
The advantages of a normal synchronous design are linearity and simplicity, but the disadvantage is that the entire program execution can easily get stuck on some time-consuming operations.
console.log(1);
readSomeFiles(); // time-consuming operations
console.log(2);
the CPU spends most of its time waiting for I/O
threads are blocked
concurrency is poor
So, in order to better utilize the CPU and more rationally allocate timer tasks and simple ordinary tasks, the concept of the event loop was born.
Systems that use event loops typically operate like this (Think about how you usually write JavaScript code):
console.log(1);
setTimeout(() => console.log(2));
Promise.resolve().then(() => {
console.log(3);
});
console.log(4);
- Execute synchronous code.
- Encounter asynchronous tasks (timers, network).
- Hand over the asynchronous task to the system for processing.
- The main thread continues execution.
- After the asynchronous task is completed, add the callback to the queue.
- Event Loop check: Is the call stack empty? If empty, retrieve the task from the queue and execute it.
In actual system implementation, complexity can arise due to the diversity of tasks. For example, JavaScript engines may divide tasks into macro tasks and micro tasks based on the actual use case in order to respond to various callbacks more effectively. (The meaning of micro tasks is to execute them as quickly as possible without interrupting the current code, A macro quest is a relatively complete task)
For a JavaScript engine:
- Execute a macro task
- Execute all micro tasks
- Browser renders the UI
- Begin the next round of the Event Loop
You can try the following code to understand event loop:
answer: 1 3 2 timeout
When a microtask is being executed, it will continue to execute as soon as a new microtask is discovered until the microtask queue is completely empty.
setTimeout(() => {
console.log("timeout");
});
Promise.resolve().then(() => {
console.log(1);
Promise.resolve().then(() => {
console.log(2);
});
});
Promise.resolve().then(() => {
console.log(3);
});
So, a classic question: Does setTimeout(fn, 0) really execute after 0ms? It does not execute after 0ms. In reality, it will be affected by factors such as the current task's duration, the number of microtasks, and the browser's minimum time slice.


Top comments (0)