JS is sync + single-threaded
The starting truth — one thread, one stack.
- One thread, one call stack, one operation at a time.
- Line N only runs after line N-1 finishes completely.
- V8 has three parts: call stack (LIFO), memory heap, garbage collector.
- The GEC (Global Execution Context) is the first frame pushed onto the stack.
Sync vs async
One hand vs ten hands.
- Sync: total time = sum of all tasks; each task waits for the previous.
- Async: total time = longest single task; tasks run independently.
- JavaScript is synchronous by itself — async is a Node.js feature, not a V8 one.
- Async work: API calls,
setTimeout, file I/O, DB queries, DNS lookups.
V8 execution in two phases
Every execution context does both.
- Memory creation phase: vars allocated as
undefined, functions stored in full. - Code execution phase: values assigned, code runs line by line.
- Function call → new Function Execution Context pushed on top of the stack.
- Function return → FEC popped; GC may reclaim that context’s memory.
libuv — the superhero
The C library that gives Node its powers.
- C library bundled inside Node; V8 can’t talk to the OS, libuv does.
- Provides the event loop, the thread pool, file I/O, networking, timers.
- V8 offloads async ops to libuv and keeps executing — never blocks.
- When an async op finishes, libuv hands the callback to the event loop.
Event loop + queues
How callbacks come home.
- Event loop rule: “Is the call stack empty?” → if yes, pull next callback onto stack.
- Two queues: macrotasks (
setTimeout, I/O callbacks) and microtasks (promises,queueMicrotask). - Microtasks always run before the next macrotask.
- This is why
Promise.thenbeatssetTimeout(…, 0)even when scheduled later.
Comments
Comments are disabled in this environment. Set
PUBLIC_GISCUS_REPO,PUBLIC_GISCUS_REPO_ID, andPUBLIC_GISCUS_CATEGORY_IDto enable.