InkdownInkdown
Start writing

core

4 files·0 subfolders

Shared Workspace

core
DNS

Event loop

Shared from "core" on Inkdown

JavaScript Event Loop — Concise Notes

Core Idea

The event loop is the runtime mechanism that allows JavaScript to handle asynchronous work without blocking the main thread.

JavaScript itself is single-threaded: it has one main call stack for executing code. The event loop coordinates the call stack, async runtime APIs, task queues, and callback execution.

One-Sentence Definition

The event loop is the orchestration system that decides when asynchronous callbacks are moved from queues back onto the call stack for execution.

Main Components

1. Call Stack

The call stack is where synchronous JavaScript code runs.

It works like a stack:

Text
Event loop
programming-language-concepts.md
zero-language-explanation.md
Last function in → first function out

Only one thing can execute on the call stack at a time.

2. Runtime APIs

In the browser, these are commonly called Web APIs.

Examples:

  • setTimeout
  • setInterval
  • fetch
  • DOM events
  • browser rendering APIs

These are provided by the environment, not by the JavaScript language itself.

In Node.js, similar async work is handled by Node/libuv APIs:

  • file system
  • networking
  • timers
  • DNS
  • HTTP
  • sockets
3. Queues

When async work completes, its callback does not immediately run. It waits in a queue.

There are two important queue types:

QueueExamplesPriority
Microtask QueuePromise.then, queueMicrotaskHigher
Macrotask Queue / Task QueuesetTimeout, setInterval, eventsLower

Microtasks are processed before macrotasks.

4. Event Loop

The event loop continuously checks:

Text
Is the call stack empty?

If yes, it allows queued callbacks to move onto the call stack.

Browser Event Loop Flow

Text
1. Run synchronous code on the call stack
2. Send async operations to Web APIs
3. Async operation completes
4. Callback enters the correct queue
5. Event loop checks if call stack is empty
6. Run all microtasks first
7. Run one macrotask
8. Browser may render
9. Repeat

Simple Diagram

Rendering diagram…

Microtasks vs Macrotasks

Microtasks have priority over macrotasks.

Example:

JavaScript
console.log("sync");

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

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

console.log("end");

Output:

Text
sync
end
promise
timeout

Why?

  1. Synchronous code runs first.
  2. Promise callback goes to the microtask queue.
  3. setTimeout callback goes to the macrotask queue.
  4. Microtasks run before macrotasks.

Key Rule

Text
Synchronous code first
Then all microtasks
Then one macrotask
Repeat

Node.js Event Loop

Node.js has a more structured event loop because it is built around libuv.

The major phases are:

Text
1. timers
2. pending callbacks
3. idle / prepare
4. poll
5. check
6. close callbacks

Node.js Phases

PhaseWhat Runs
TimerssetTimeout, setInterval
Pending CallbacksSome deferred I/O callbacks
Idle / PrepareInternal Node.js work
PollMost I/O callbacks
ChecksetImmediate
Close CallbacksClose events like socket.on("close")

Node.js Special Case: process.nextTick

In Node.js, process.nextTick() has even higher priority than normal Promise microtasks.

Example:

JavaScript
process.nextTick(() => console.log("nextTick"));

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

setTimeout(() => console.log("timeout"), 0);

Output:

Text
nextTick
promise
timeout

Priority order in Node.js:

Text
process.nextTick
Promise microtasks
Macrotasks / event loop phases

Browser vs Node.js

AspectBrowserNode.js
Runtime APIsWeb APIslibuv / Node APIs
Async Examplestimers, fetch, DOM eventstimers, fs, http, DNS
MicrotasksPromises, queueMicrotaskPromises, queueMicrotask
Special PriorityMutationObserverprocess.nextTick
Extra Task TypeBrowser renderingsetImmediate

Correct Mental Model

The event loop is not just one object or one queue.

It is the coordination process between:

Text
Call Stack
Runtime APIs
Microtask Queue
Macrotask Queue
Callback Execution

Together, these allow JavaScript to appear asynchronous while still executing JavaScript code on a single main thread.

Final Recap

JavaScript runs synchronous code on one call stack. Async work is handled by the runtime environment. When async work finishes, callbacks enter queues. The event loop waits for the stack to become empty, then executes queued callbacks in priority order.

In short:

Text
The event loop is the architecture that makes asynchronous JavaScript possible.