Back to series
· 12 min read

Event Loop


1. What Is an Event Loop?

An event loop is a scheduling mechanism used to manage the execution order of asynchronous tasks.

It typically runs in a single thread and is responsible for coordinating:

  • The execution of synchronous code.
  • The registration of asynchronous tasks.
  • The scheduling of callback functions.
  • The triggering of timer tasks.
  • The handling of results after I/O operations complete.
  • The resumption of Promises, Futures, and coroutines.

The most important role of the event loop is: when a task needs to wait for I/O, a timer, or another asynchronous operation, the executing thread does not have to remain occupied — instead, it can continue processing other executable tasks.

For example, in JavaScript:

console.log("Start");

setTimeout(() => {
    console.log("Timer callback");
}, 1000);

console.log("End");

Output:

Start
End
Timer callback

Although the timer callback is registered before the final console.log in the code, it does not execute immediately.

The JavaScript main thread first executes the current synchronous code; only after the timer expires does the callback get a chance to enter the subsequent scheduling process of the event loop.

1.1 Why Is an Event Loop Needed?

Traditional synchronous programs typically execute in code order.

Suppose a program needs to perform three operations:

  1. Read a file.
  2. Request a remote API.
  3. Compute the result.

If all operations are blocking, the thread may be unable to perform other tasks while waiting for file and network responses.

The event loop improves this situation through asynchronous mechanisms.

flowchart TB
    A["Start executing a task"] --> B["Initiate asynchronous I/O"]
    B --> C["Register completion callback"]
    C --> D["Thread continues executing other tasks"]
    D --> E["I/O operation proceeds in the background"]
    E --> F["I/O operation completes"]
    F --> G["Callback enters the executable queue"]
    G --> H["Event loop schedules the callback"]
    H --> I["Process the I/O result"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Note:

An event loop does not mean that asynchronous operations themselves are necessarily executed by the event loop thread.

Network I/O, file I/O, timers, and other asynchronous operations may be handled by the operating system, a runtime thread pool, or a dedicated I/O mechanism. The event loop is primarily responsible for scheduling the subsequent processing after these operations complete.


2. Core Components of an Event Loop

Event loop implementations differ across languages and runtimes, but they can generally be understood through the following concepts.

2.1 Call Stack

The call stack is used to manage the function calls currently being executed.

When a function is called, a corresponding stack frame is created; when the function finishes executing, the stack frame is popped.

For example:

function first() {
    second();
}

function second() {
    console.log("Executing second");
}

first();

Execution process:

Call first()
    |
    v
first() pushed onto the stack
    |
    v
Call second()
    |
    v
second() pushed onto the stack
    |
    v
Execute console.log()
    |
    v
second() popped from the stack
    |
    v
first() popped from the stack

Tasks in the call stack are typically managed on a last-in, first-out (LIFO) basis.

In JavaScript, while the current synchronous call stack has not finished executing, the event loop will not interrupt ordinary JavaScript code to execute another callback.

2.2 Task Queue

The task queue is used to store tasks or callbacks waiting to be executed.

Common task sources include:

  • Timers.
  • User interaction events.
  • Network request completion events.
  • File operation completion events.
  • Message passing.
  • Promise follow-up handling.

There is not necessarily only one task queue.

For example, JavaScript divides tasks into macrotasks and microtasks, whereas Python asyncio uses callback queues and timer management structures inside the event loop.

Therefore, the event loop of every language cannot be understood as a simple FIFO queue.

2.3 Event Loop

The event loop is responsible for continuously checking whether there are runnable tasks and executing them according to the scheduling policy defined by the runtime.

A simplified event loop model:

flowchart TB
    A["Event loop starts"] --> B{"Is the call stack idle?"}
    B -->|"No"| C["Continue executing the current code"]
    C --> B
    B -->|"Yes"| D["Check for runnable tasks"]
    D --> E{"Are there any tasks?"}
    E -->|"Yes"| F["Take a task and execute it"]
    F --> B
    E -->|"No"| G["Wait for new events or tasks"]
    G --> D

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style C fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

This is an abstract model for understanding. Real runtimes may have multiple task queues, different priorities, phase divisions, and specialized I/O polling mechanisms.

2.4 Asynchronous Task Sources (Async Sources)

Asynchronous task sources are responsible for producing events that need to be processed later.

For example:

Task Source Typical Scenario
Timer Timer expires
Network I/O Network request completes
File I/O File read completes
User Event Mouse click, keyboard input
Message Message channel receives data
Promise / Future Asynchronous operation completes
Socket Network connection or data becomes readable/writable

These task sources usually cooperate with the operating system and the runtime.


3. Complete Workflow of the Event Loop

The operation of the event loop can be divided into several phases.

3.1 Registering Asynchronous Tasks

When a program performs an asynchronous operation, it first submits a task to the runtime.

For example:

setTimeout(() => {
    console.log("定时器完成");
}, 1000);

The runtime registers the timer and its callback.

The current JavaScript call stack does not need to wait for one second and can continue executing the code that follows.

3.2 Waiting for Asynchronous Operations to Complete

Asynchronous operations may be executed by different mechanisms:

  • Operating system asynchronous I/O.
  • Runtime-internal thread pools.
  • Network protocol stack.
  • Timer facilities.
  • Web APIs provided by the browser.

These mechanisms are responsible for waiting for the operation to complete and notifying the runtime.

3.3 Adding Callbacks to the Scheduling Queue

When an asynchronous operation meets its trigger condition, the corresponding callback enters the runnable queue or task scheduling structure defined by the runtime.

It is important to note that a task completing and a callback executing immediately are two different things.

If the current thread is executing time-consuming synchronous code, even if the timer has already expired, the callback may not be able to execute immediately.

3.4 Event Loop Scheduling Tasks

The event loop selects runnable tasks based on task type and scheduling rules.

In JavaScript, special attention should be paid to the distinction between macrotasks and microtasks.

In Python asyncio, attention should be paid to the scheduling of ready callbacks, timers, and coroutine tasks.

3.5 Executing Callbacks and Resuming Tasks

After the event loop executes a callback, the callback may:

  • Handle the result of the asynchronous operation.
  • Modify program state.
  • Create new asynchronous tasks.
  • Register new timers.
  • Continue waiting for other I/O operations.

Complete workflow:

flowchart TB
    A["Execute synchronous code"] --> B["Initiate an asynchronous operation"]
    B --> C["Runtime registers a task"]
    C --> D["Asynchronous operation waits for completion"]
    D --> E["Operation completes and generates an event"]
    E --> F["Callback enters the scheduling queue"]
    F --> G{"Is the current execution thread idle?"}
    G -->|"No"| H["Wait for the current task to complete"]
    H --> G
    G -->|"Yes"| I["Event loop takes a task"]
    I --> J["Execute callback or resume coroutine"]
    J --> K{"Is a new asynchronous task generated?"}
    K -->|"Yes"| B
    K -->|"No"| L["Continue checking other tasks"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style K fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style L fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

4. JavaScript Event Loop: Macrotasks and Microtasks

The JavaScript event loop is one of the most typical examples for understanding asynchronous programming.

In browser environments, the event loop is defined by the HTML standard; in Node.js, the event loop is implemented jointly by components such as Node.js and libuv.

The two share similar concepts, but their specific scheduling phases are not exactly the same.

4.1 Macrotasks (Macrotask / Task)

Macrotasks are a type of task scheduled by the JavaScript runtime.

Common sources include:

  • Overall script execution.
  • setTimeout().
  • setInterval().
  • User interaction events.
  • Some I/O callbacks.
  • Message events.

For example:

console.log("同步任务 1");

setTimeout(() => {
    console.log("宏任务");
}, 0);

console.log("同步任务 2");

Output:

同步任务 1
同步任务 2
宏任务

setTimeout(..., 0) does not mean the callback executes immediately.

It means that only after the timer meets the minimum delay condition is the callback eligible to enter subsequent task scheduling.

Actual execution is also affected by the current call stack, task scheduling, and runtime load.

4.2 Microtasks (Microtask)

Microtasks are tasks that need to be processed after the current task finishes executing and before the browser continues with subsequent tasks.

Common microtask sources include:

  • Promise.then().
  • Promise.catch().
  • Promise.finally().
  • queueMicrotask().
  • MutationObserver callbacks.

For example:

console.log("同步任务");

setTimeout(() => {
    console.log("宏任务");
}, 0);

Promise.resolve().then(() => {
    console.log("微任务");
});

console.log("同步任务结束");

Output:

同步任务
同步任务结束
微任务
宏任务

The reason is that after the current script task finishes executing, the runtime first performs the microtask checkpoint before proceeding to subsequent task scheduling.

4.3 Execution Order of Macrotasks and Microtasks

In browser JavaScript, the typical scheduling process can be summarized as follows:

  1. Execute the current task.
  2. The current task finishes executing.
  3. Perform the microtask checkpoint and process microtasks.
  4. If microtasks generate further microtasks during execution, continue processing them.
  5. After the microtask queue is emptied, the browser has an opportunity to render.
  6. Continue selecting subsequent tasks.
flowchart TB
    A["Start executing the current Task"] --> B["Execute synchronous code"]
    B --> C["Current Task ends"]
    C --> D["Execute Microtask Queue"]
    D --> E{"Are there any more microtasks?"}
    E -->|"Yes"| F["Execute next microtask"]
    F --> D
    E -->|"No"| G["Browser can render"]
    G --> H["Select next Task"]
    H --> A

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Note:

  • Microtasks usually have a higher scheduling priority than subsequent ordinary tasks.
  • When the microtask queue keeps producing new tasks, it may remain unable to be emptied for a long time.
  • Only after microtasks finish executing does the browser have a chance to render.
  • The browser does not necessarily render once after each macrotask.

4.4 Why can microtasks cause page lag?

Consider the following code:

function loop() {
    Promise.resolve().then(loop);
}

loop();

Each time a microtask executes, it creates a new microtask.

Because the microtask checkpoint must continuously process newly generated microtasks, the queue may never be emptied.

This can prevent the browser from reaching subsequent task scheduling and rendering opportunities.

The result may be:

  • The page cannot refresh in time.
  • User click events cannot be responded to in time.
  • Animations stutter.
  • CPU is occupied for a long time.

Therefore, a large amount of continuous computation should not all be placed in microtasks.

If you need to execute work in batches, consider:

  • setTimeout().
  • MessageChannel.
  • requestAnimationFrame().
  • requestIdleCallback() (browser support needs to be considered).

4.5 Overall Execution Order Example

console.log("1");

setTimeout(() => {
    console.log("2");

    Promise.resolve().then(() => {
        console.log("3");
    });
}, 0);

Promise.resolve().then(() => {
    console.log("4");
});

console.log("5");

Output:

1
5
4
2
3

Analysis:

Order Execution Reason
1 Output 1 Synchronous code
2 Register timer Callback is not executed immediately
3 Register Promise microtask Waits for the current task to end
4 Output 5 Synchronous code continues executing
5 Output 4 Execute the microtask after the current task ends
6 Output 2 The timer callback enters subsequent task scheduling
7 Output 3 The microtask created by the timer callback executes after that callback task ends

This example shows that microtasks can be created not only by the initial synchronous code but also during the execution of a macrotask callback.


V. The Event Loop and Browser Rendering in JavaScript

The browser event loop not only manages JavaScript tasks but also coordinates page rendering.

5.1 Main Browser Execution Flow

When the browser processes a page, this involves:

  • JavaScript execution.
  • DOM updates.
  • CSS style calculation.
  • Layout.
  • Paint.
  • Composite.

The event loop provides the browser with opportunities to schedule task execution and rendering.

Simplified process:

flowchart TB
    A["Execute JavaScript Task"] --> B["Execute Microtasks"]
    B --> C{"Has a rendering opportunity arrived?"}
    C -->|"No"| D["Continue processing subsequent tasks"]
    C -->|"Yes"| E["Process styles and layout"]
    E --> F["Paint the page"]
    F --> G["Composite and display"]
    G --> D
    D --> H["Select the next Task"]
    H --> A

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style D fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

This is only a conceptual flow. In practice, browser rendering timing is affected by refresh rate, page visibility, task scheduling, and browser implementation.

5.2 requestAnimationFrame

requestAnimationFrame() is used to request that the browser execute a callback at the next rendering opportunity suitable for animation updates.

For example:

function animate(timestamp) {
    updateAnimation(timestamp);

    requestAnimationFrame(animate);
}

requestAnimationFrame(animate);

Suitable for:

  • Canvas animations.
  • DOM animations.
  • Game rendering.
  • Visual updates that need to be coordinated with the screen refresh rhythm.

How it differs from setTimeout():

Comparison setTimeout requestAnimationFrame
Primary use Delay callback execution Coordinate with browser rendering
Scheduling method Timer task Callback tied to rendering opportunities
Timing control Specifies a minimum delay Determined by the browser's rendering cadence
Background tab May be throttled Usually pauses or reduces frequency
Typical scenario Delayed operations Animation updates

requestAnimationFrame() does not equal a fixed 60 FPS, nor does it guarantee that callbacks will execute at a fixed interval.

5.3 Causes of page jank

Suppose the browser's main thread is executing a synchronous task that takes 200 ms.

During this time:

  • JavaScript cannot respond to new tasks in a timely manner.
  • User interaction events cannot be handled in a timely manner.
  • Page rendering opportunities may be missed.
  • Animations may visibly stutter.

For example:

const start = Date.now();

while (Date.now() - start < 200) {
    // Simulate a long synchronous computation
}

console.log("计算完成");

Such long tasks block the main thread.

Solutions include:

  • Split tasks into multiple smaller tasks.
  • Use Web Workers to perform CPU-intensive computations.
  • Use appropriate scheduling APIs.
  • Reduce unnecessary synchronous computation.
  • Avoid occupying the microtask queue for extended periods.

6. Event Loop in Node.js

Node.js also uses an event loop model, but its implementation is not exactly the same as that in browsers.

Node.js's event loop relies on important low-level support provided by libuv, which coordinates I/O, timers, callbacks, and other work.

6.1 Phases of the Node.js Event Loop

The Node.js event loop consists of multiple phases:

Phase Main purpose
Timers Execute eligible setTimeout and setInterval callbacks
Pending Callbacks Execute some system-level I/O callbacks deferred to the current loop iteration
Idle / Prepare Phase used internally by libuv
Poll Retrieve new I/O events and execute related callbacks
Check Execute setImmediate() callbacks
Close Callbacks Execute some close-event callbacks

Among these, the Poll phase handles I/O-related events and is an important part of the Node.js event loop.

Simplified phase diagram:

flowchart TB
    A["Timers"] --> B["Pending Callbacks"]
    B --> C["Idle / Prepare"]
    C --> D["Poll"]
    D --> E["Check"]
    E --> F["Close Callbacks"]
    F --> A

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

This is a simplified phase loop diagram for easier understanding; it does not mean that callbacks are executed in every phase on each iteration.

Node.js version upgrades may affect the exact timing of some phases. For example, starting with libuv 1.45, which Node.js 20 uses, the timing of timer handling has been adjusted, so descriptions from older versions of the relative order of Timers and Poll cannot simply be applied.

6.2 process.nextTick()

Node.js provides process.nextTick() to schedule a callback to run in the next tick phase after the current operation completes.

For example:

console.log("开始");

process.nextTick(() => {
    console.log("nextTick");
});

Promise.resolve().then(() => {
    console.log("Promise");
});

console.log("结束");

In a typical Node.js environment, the output is:

开始
结束
nextTick
Promise

process.nextTick() is not an ordinary phase in the libuv event loop.

It has its own callback queue and special scheduling timing.

Continually calling process.nextTick() recursively may prevent the event loop from proceeding to subsequent phases in a timely manner.

6.3 setImmediate()

setImmediate() schedules a callback to execute in the Check phase of the event loop.

For example:

setImmediate(() => {
    console.log("Immediate");
});

setTimeout(() => {
    console.log("Timeout");
}, 0);

In top-level code, the order of these two callbacks may be affected by runtime startup time and scheduling conditions, so you should not rely on a fixed output order.

If both are scheduled inside an I/O callback, you can usually observe setImmediate() executing before setTimeout(..., 0), because the former is scheduled for the Check phase of the current loop iteration, while the latter must wait for the timer phase to satisfy its execution conditions.

6.4 Node.js Thread Pool and Event Loop

In Node.js, not all asynchronous operations are completed on the event loop thread.

For example, some file system operations, cryptographic operations, and DNS operations may use the libuv thread pool.

Network I/O, by contrast, usually uses asynchronous or event notification mechanisms provided by the operating system.

Simplified architecture:

flowchart TB
    A["JavaScript Main Thread"] --> B["Node.js Event Loop"]
    B --> C["Timer Callbacks"]
    B --> D["Network I/O Events"]
    B --> E["Thread Pool Task Completion Notifications"]
    F["libuv Thread Pool"] --> G["File System and Some Compute Tasks"]
    G --> E
    H["OS Network I/O"] --> D
    C --> I["Execute JavaScript Callbacks"]
    D --> I
    E --> I

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

This also explains why Node.js can handle a large number of I/O requests with just a small number of JavaScript execution threads.

But CPU-intensive JavaScript code can still block the main thread.


7. The Event Loop in Python asyncio

Python's asyncio is an important tool for asynchronous programming built on the event loop.

It uses coroutines, Tasks, Futures and the event loop to manage asynchronous tasks.

7.1 Core Components of asyncio

Concept Purpose
Event Loop Manages and schedules asynchronous tasks
Coroutine A coroutine object defined with async def
Task Wraps a coroutine into a schedulable task
Future Represents an asynchronous result that has not yet completed
await Suspends the current coroutine and waits for the asynchronous result

For example:

import asyncio

async def fetch_data():
    print("开始请求")

    await asyncio.sleep(1)

    print("请求完成")
    return "data"


async def main():
    result = await fetch_data()
    print(result)


asyncio.run(main())

asyncio.sleep(1) does not block the entire event loop thread the way the traditional time.sleep(1) does.

It suspends the current coroutine and gives the event loop a chance to schedule other tasks.

7.2 How Do Coroutines Work with the Event Loop?

When a coroutine reaches an await whose operation has not yet completed, the current coroutine is suspended for the time being.

The event loop can then schedule other tasks that are already ready.

Once the awaited operation completes, the original coroutine becomes executable again.

flowchart TB
    A["Event loop schedules Task A"] --> B["Execute coroutine A"]
    B --> C["Encounter await"]
    C --> D{"Has the awaited operation completed?"}
    D -->|"No"| E["Suspend coroutine A"]
    E --> F["Schedule other ready tasks"]
    F --> G["Async operation completes"]
    G --> H["Coroutine A becomes ready again"]
    H --> I["Resume coroutine A"]
    I --> J["Continue executing subsequent code"]
    D -->|"Yes"| J

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px