FullStack AI Hub
Studio
Frontend & Browser · 01. Browser & Rendering Engine
9 min
6 steps
Beginner

JS Event Loop & Main Thread Scheduling

Master macrotasks, microtasks, Interaction to Next Paint (INP), cooperative yielding, and Web Worker offloading.

Frontend & Browser01. Browser & Rendering EngineLesson 2 of 2
9 minBeginner6 steps

JS Event Loop & Main Thread Scheduling

Master macrotasks, microtasks, Interaction to Next Paint (INP), cooperative yielding, and Web Worker offloading.

INP (P75)
14 ms
Max Task
9 ms
Paint Pacing
60 fps
Blocked Time
0 ms
Event Loop & 16.6ms Browser Frame Lab
Tick 1/7 · t = 1 ms
Phase: Sync Call Stack

Synchronous script runs first on the Call Stack and logs "1. Sync Start".

Script ExecutionSync → Microtask → rAF Paint → Macrotask
1console.log("1. Sync Start");
2setTimeout(() => console.log("4. Macrotask"), 0);
3Promise.resolve().then(() => console.log("3. Microtask"));
4requestAnimationFrame(() => paintFrame());
5console.log("2. Sync End");
Console & Paint Log1 entries
  • 1. Sync Start
Call Stack (LIFO)2
main()
console.log("1. Sync Start")
Microtask Queue0

Drains to 0 before Paint or Macrotasks.

Drained (0)
Macrotasks & Web APIs0
No Queued Macrotasks
16.6 ms VSync Frame Budget Timeline (60 fps)
INP: 14 msDropped Frames: 0Effective: 60 fps
MAIN THREAD (0 ms → 34 ms)WORKER THREAD17msSync ScriptMicrotasks (1)rAF + PaintsetTimeout
In This LessonStep 1 of 6
What You Will Master
  • ✓Order execution across the Call Stack, Microtask Queue, Macrotask Queue, and rAF paint step
  • ✓Understand how 250 ms Long Tasks block clicks and degrade Interaction to Next Paint (INP)
  • ✓Break up heavy UI work using `scheduler.yield()` and React concurrent transitions
  • ✓Offload CPU-heavy parsing, search indexing, and encryption to dedicated Web Workers

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Microtask (`Promise.then`)Immediate async state continuations before next paintRecursive microtasks starve painting and freeze the tab completely
Cooperative YieldingSplitting medium 150 ms UI updates into <50 ms chunksLets urgent clicks paint between chunks without worker serialization
Web Worker ThreadFuzzy search, CSV/JSON parsing, crypto, and canvas layout mathNo direct DOM access; transfer large buffers via `Transferable`
Concurrent TransitionKeeping typing input responsive while filtering large listsRequires clear pending indicator so slow filter updates feel intentional

Step-by-Step Architectural Breakdown (6 Steps)

Full architectural walkthrough transcript and state transitions for JS Event Loop & Main Thread Scheduling.

STEP 01 · SETUPJump to step →

One Main Thread Sharing JS, Input & Paint

Every browser tab runs user clicks, JavaScript execution, Promise microtasks, and frame painting on **one single Main Thread**. After each task completes, the loop drains all microtasks before checking if it is time to paint.

idea:Click Play Ticks or Step Forward on the stage to watch Sync → Microtasks → rAF Paint → Macrotask execute in exact browser spec order.

Call StackMicrotask QueueMacrotask QueueRender Step
STEP 02 · PROBLEMJump to step →

Long Tasks & Interaction to Next Paint (INP) Freeze

Parsing a 4 MB JSON payload or synchronously re-rendering 2,000 table cells creates a 250+ ms **Long Task**. User clicks sit trapped in the queue while the screen misses 15 VSync frames—failing Google’s Core Web Vitals INP threshold (200 ms).

watch:Any task over 50 ms is classified as a Long Task; drag the Long Task Duration slider or trigger Microtask Storm to see VSync frames drop live.

Long Task (>50ms)INP Core Web VitalInput DelayMain Thread Starvation
STEP 03 · SOLUTIONJump to step →

Breaking Up Work with `scheduler.yield()`

Split non-urgent work into small chunks and call **`await scheduler.yield()`** (or wrap React state updates in `startTransition`). Urgent user clicks jump straight to the front of the line and paint immediately inside the 16.6 ms budget.

good:`scheduler.yield()` lets high-priority clicks and paints run while preserving your continuation ahead of low-priority background scripts.

scheduler.yield()startTransitionPrioritized SchedulingChunked Rendering
STEP 04 · TECHNIQUEJump to step →

Offloading Heavy Compute to Web Workers

For CPU-intensive tasks—like Fuse.js search indexing, diffing large ASTs, or crunching CSV exports—move execution onto a dedicated **Web Worker** OS thread so the Main Thread stays 100% free for 60fps UI interaction.

idea:Watch the Worker Thread lane below the Main Thread timeline: 220 ms of CPU work finishes off-thread with zero dropped animation frames.

Web WorkerStructured CloneTransferable ArrayBufferOff-Main-Thread
STEP 05 · TRADE-OFFJump to step →

When NOT to Use a Web Worker (Microtask & Clone Pitfalls)

Calling `postMessage` on huge nested JS objects runs **structured cloning**, which can block the main thread longer than doing the small calculation inline! Likewise, endless chained `.then()` microtasks starve rendering just like synchronous loops.

watch:Never chat with a Worker 60 times a second with giant JSON payloads—batch messages or pass binary `ArrayBuffer` transferables, and avoid unbounded Promise loops.

Serialization OverheadMicrotask StarvationArrayBufferMain Thread vs Worker
STEP 06 · RECAPJump to step →

Main Thread Responsiveness Recap

Protect the Main Thread like a precious single-core CPU: keep tasks under 50 ms, yield non-urgent rendering with `scheduler.yield()`, and offload heavy pure computation to Web Workers.

good:Use the scenario switcher above to compare Queue Ordering, 250ms Long Tasks, Microtask Storms, Cooperative Yielding, and Web Workers side by side.

INP OptimizationMain Thread HygieneYieldingWeb Workers

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.