Skip to main content
CSArchitecture & RuntimeInteractiveIntermediate

Event Loop

KO: 이벤트 루프·EN: Event Loop·JA: イベントループ

A runtime mechanism that achieves non-blocking concurrency on a single thread by continuously pulling completed async callbacks from queues into an empty call stack

Table of Contents

Interactive Playground

Tap or drag to interact with the demo
Quick Answer

What is Event Loop?

A runtime mechanism that achieves non-blocking concurrency on a single thread by continuously pulling completed async callbacks from queues into an empty call stack. It is a core concept in Architecture & Runtime within CS.

Core Principles

The Event Loop is the scheduling engine that lets single-threaded runtimes—such as web browsers, Node.js (libuv), and Python asyncio—handle thousands of concurrent I/O operations and UI interactions without freezing.

While synchronous code runs on the Call Stack, slow operations like fetch, timers, and file I/O are offloaded to browser Web APIs or OS kernel polling (epoll/kqueue). When those operations finish, their callbacks wait in queues. Whenever the Call Stack becomes empty, the Event Loop ticks in a strict priority order:

  1. Drain the entire Microtask Queue (Promise.then, queueMicrotask) until completely empty.
  2. Pull one callback from the Macrotask Queue (setTimeout, DOM events, I/O callbacks), execute it, and yield to browser rendering if a frame is due.

Practical Takeaways

  • Never block the main thread: Because the loop cannot advance until the current synchronous function returns, any CPU-heavy work exceeding ~50ms (large JSON parsing, cryptography, image processing) will freeze UI frames or spike server p99 latency. Offload heavy compute to Web Workers or Node Worker Threads.
  • Understand microtask priority and starvation: Promise.resolve().then(...) always runs before setTimeout(..., 0). Be careful not to schedule recursive microtasks endlessly, or browser paints and click handlers will starve.
  • Shine on I/O-bound workloads: Event-loop servers excel at juggling tens of thousands of idle sockets and API calls with minimal RAM, avoiding thread-context-switching overhead and lock contention.

Notable Examples

  • Browser main thread: Coordinating DOM events, fetch responses, requestAnimationFrame, and UI rendering at 60fps.
  • Node.js & Nginx: Handling massive concurrent HTTP and WebSocket connections via non-blocking event-driven I/O.
  • Redis & Python asyncio: Leveraging a single-threaded event loop to achieve predictable, lock-free throughput.

Practical Code Snippet

Copy and drop straight into your project
event-loop-order.tsTypeScript
console.log("1. Sync (Call Stack)"); setTimeout(() => {  console.log("4. Macrotask (Task Queue)");}, 0); Promise.resolve().then(() => {  console.log("3. Microtask (Promise Queue)");}); console.log("2. Sync (Call Stack)");// Output: 1 -> 2 -> 3 -> 4