DEV Community

Cover image for Some basic understanding of event loop
E_Chronosands::
E_Chronosands::

Posted on

Some basic understanding of event loop

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode
  1. Execute synchronous code.
  2. Encounter asynchronous tasks (timers, network).
  3. Hand over the asynchronous task to the system for processing.
  4. The main thread continues execution.
  5. After the asynchronous task is completed, add the callback to the queue.
  6. 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:

  1. Execute a macro task
  2. Execute all micro tasks
  3. Browser renders the UI
  4. 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);
});
Enter fullscreen mode Exit fullscreen mode

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)