The Main Thread: why one long function can freeze the UI
| Main-thread work | What it can delay | Example |
|---|---|---|
| JavaScript | Input and handlers | Large data parsing, framework render |
| Style calculation | Next paint | Broad style invalidation |
| Layout | Next paint | Large DOM, forced layout |
| Paint | Frame presentation | Large repaint area |
The browser main thread handles most page JavaScript, user events, style calculation, layout and paint. MDN emphasizes that long-running JavaScript blocks the same thread needed for input handling and rendering. [4]
JavaScript work is effectively run-to-completion: a task that has started is not automatically interrupted in the middle so a click can be processed. If the user interacts during heavy work, the event waits.
Responsiveness therefore depends not only on total CPU work but also on how that work is scheduled over time.
What a Long Task is, and why 50 ms is not a performance target
| Situation | Can it hurt INP? | Why |
|---|---|---|
| One 200 ms task | Yes | Blocks input and rendering |
| Four 45 ms tasks | Yes | May consume successive input opportunities |
| Short handler + expensive layout | Yes | Presentation delay grows |
| Long task with no interaction | Maybe | The next interaction may arrive during it |
MDN describes a Long Task as uninterrupted work occupying the UI thread for 50 ms or more. Typical sources include long event handlers, expensive reflows and other browser work between event-loop turns. [6]
The 50 ms threshold is useful for diagnosis, but it does not mean 49 ms is always safe or that every 51 ms task should be split at exactly the same point.
Several shorter tasks can still occupy an animation frame or delay input, which is why modern diagnostics also use Long Animation Frames. [7]
What INP actually measures
INP is a stable Core Web Vital that observes qualifying click, tap and keyboard interaction latency across the page lifecycle. For most pages the slowest interaction is reported, while very interaction-heavy pages ignore some extreme outliers. [1]
A good INP is 200 ms or less, above 200 ms through 500 ms needs improvement, and above 500 ms is poor. Core Web Vitals assessment uses the 75th percentile of page views, segmented by mobile and desktop. [1][2]
Scrolling and hovering are not included. INP measures from user input until the browser can present the next frame associated with that interaction. [1]
For every 50 interactions, the slowest remaining interaction is excluded. A single visit’s result is not the 75th percentile across visits. If there is no qualifying interaction, INP may be absent; do not replace missing data with zero. The metric does not cover the entire network response or every subsequent UI update. [1]
Three parts of a slow interaction: input delay, processing and presentation delay
| INP subpart | Typical meaning | Check first |
|---|---|---|
| Input delay | Main thread was already busy | Other scripts, timers, startup, prior interactions |
| Processing duration | Handler does too much | Event code, framework update, synchronous compute |
| Presentation delay | Rendering is expensive | Style, layout, paint, large DOM |
web.dev splits an interaction into input delay, processing duration and presentation delay. Together they make up total interaction latency. [2]
Input delay runs from the user action until event callbacks begin. Processing duration is the time those callbacks execute. Presentation delay starts when callbacks finish and ends when the next frame is presented.
This decomposition matters because optimizing the handler will not help if the real problem is work already occupying the main thread or expensive rendering after the handler.
Hypothetical example: a 320 ms interaction consists of 180 ms input delay, 40 ms processing and 100 ms presentation delay. First inspect the task blocking the thread before the handler, then rendering cost. Halving the handler time would save only 20 ms in this simplified model. After changes, reproduce the same interaction in DevTools and compare field data for similar device cohorts. [2]
Remove work before splitting it
Synchronous profiling baseline (sync.mjs)
// Intentionally synchronous: a baseline for profiling, not a UI handler.
export function sumAmounts(records) {
let total = 0;
for (const { amount } of records) {
total += amount;
}
return total;
}
web.dev recommends removing unnecessary code and avoiding long-running work before reaching for scheduling techniques. Splitting a task improves responsiveness but does not automatically reduce total CPU cost. [3][5]
For an interaction, separate the work that must happen before the next frame from work that can wait. Give the user immediate feedback first, then do analytics, secondary persistence or expensive analysis afterward.
This distinction is especially important in SPAs where one state update may trigger a wide component tree update.
A large array of records with numeric amount fields may block the UI. This is a profiling baseline, not a recommended click handler. Compare it with the next version.
scheduler.yield(): modern cooperative yielding with a fallback
Chunking work with scheduler.yield() and a fallback (chunk.mjs)
const DEFAULT_BUDGET_MS = 8;
async function yieldToMain() {
const scheduler = globalThis.scheduler;
if (typeof scheduler?.yield === "function") {
await scheduler.yield();
return;
}
await new Promise((resolve) => setTimeout(resolve, 0));
}
export async function sumAmountsInChunks(
records,
{ signal, budgetMs = DEFAULT_BUDGET_MS } = {},
) {
if (!Number.isFinite(budgetMs) || budgetMs <= 0) {
throw new RangeError("The time budget must be positive and finite.");
}
signal?.throwIfAborted();
let total = 0;
let chunkStartedAt = performance.now();
for (const [index, { amount }] of records.entries()) {
signal?.throwIfAborted();
total += amount;
const hasMoreRecords = index < records.length - 1;
if (hasMoreRecords && performance.now() - chunkStartedAt >= budgetMs) {
await yieldToMain();
signal?.throwIfAborted();
chunkStartedAt = performance.now();
}
}
return total;
}
scheduler.yield() lets an async function give the main thread back to the browser and continue later. The continuation is scheduled as a prioritized task, which makes chunking work easier than manually chaining callbacks. [9]
The API still has Limited availability and is not Baseline, so production code should feature-detect it. MDN and current Chrome guidance show a setTimeout(..., 0) fallback. [9][5]
Do not yield after every statement. Excessive yielding adds overhead and can reduce overall throughput.
The 8 ms budget is illustrative, not a smoothness guarantee. The function checks elapsed time rather than record count and supports AbortSignal. Callers must handle rejection; validate records before processing. [17]
Promise.then() and queueMicrotask() do not unblock rendering
Trap: a microtask is not a rendering yield (microtask.mjs)
console.log("1. Current task");
queueMicrotask(() => {
console.log("3. Microtask");
});
setTimeout(() => {
console.log("4. Later task");
}, 0);
console.log("2. End of current task");
Microtasks run after the current task finishes but before the event loop proceeds and before the browser gets another rendering opportunity. MDN notes that the microtask queue is drained until empty. [12]
That means splitting a heavy loop with await Promise.resolve() or a chain of queueMicrotask() calls can still block input and paint.
Microtasks are useful for ordering and brief end-of-turn work, not for cooperative scheduling of long CPU work.
Run the snippet in the console: the order 1, 2, 3, 4 shows microtasks running before a later task, not a paint measurement.
Show feedback before starting heavy work
Run noncritical work after the next paint (feedback.mjs)
export function scheduleAfterFrame(callback) {
let timeoutId;
const frameId = requestAnimationFrame(() => {
timeoutId = setTimeout(callback, 0);
});
return function cancel() {
cancelAnimationFrame(frameId);
clearTimeout(timeoutId);
};
}
When an interaction must trigger substantial work, perform the minimum UI update first and move the rest until after the next paint. web.dev demonstrates that heavy work inside requestAnimationFrame() still blocks the next paint because rAF runs before rendering. [3]
A broadly compatible pattern is requestAnimationFrame() followed by setTimeout() so noncritical work begins only after the browser has had a chance to paint. [2][3]
This does not remove the heavy work, so a future interaction can still collide with it. It is a fast-feedback technique, not a complete fix.
requestIdleCallback() can be useful for low-priority background work, but MDN still marks it as Limited availability. Without a timeout, a callback can be delayed for several seconds, so it should not be the primary mechanism for work required by the current interaction. [10]
A rendering opportunity does not guarantee that a frame is presented, particularly in a hidden tab. Supply a synchronous callback and call the returned cancellation function on teardown.
Debounce, cancellation and stale work
Debouncing and canceling stale work (search.mjs)
const DEFAULT_DEBOUNCE_MS = 250;
export function attachSearch({
input,
search,
renderResults,
reportError,
delayMs = DEFAULT_DEBOUNCE_MS,
}) {
if (!(input instanceof HTMLInputElement)) {
throw new TypeError("A search input is required.");
}
if (!Number.isFinite(delayMs) || delayMs < 0) {
throw new RangeError("The debounce delay must be nonnegative and finite.");
}
let timeoutId;
let activeRequest;
function cancelPendingSearch() {
clearTimeout(timeoutId);
timeoutId = undefined;
activeRequest?.abort();
activeRequest = undefined;
}
async function executeSearch(query, controller) {
const { signal } = controller;
try {
const results = await search(query, { signal });
if (!signal.aborted && activeRequest === controller) {
renderResults(results);
}
} catch (error) {
if (!signal.aborted && activeRequest === controller) {
reportError(error);
}
} finally {
if (activeRequest === controller) {
activeRequest = undefined;
}
}
}
function handleInput() {
cancelPendingSearch();
const query = input.value.trim();
const controller = new AbortController();
activeRequest = controller;
timeoutId = setTimeout(() => {
timeoutId = undefined;
void executeSearch(query, controller).catch((error) => {
console.error("Search error handler failed:", error);
});
}, delayMs);
}
input.addEventListener("input", handleInput);
return function dispose() {
input.removeEventListener("input", handleInput);
cancelPendingSearch();
};
}
Search-as-you-type, filters and range controls can generate interactions faster than the application can process every intermediate state. Executing every obsolete version wastes CPU.
web.dev highlights debouncing and aborting stale work as useful responsiveness strategies. If new input replaces old input, cancel the old operation rather than letting it block future interactions. [3]
AbortController can cancel network requests, and custom loops can check signal.aborted between chunks.
attachSearch accepts an existing HTMLInputElement, an asynchronous search(query, { signal }) function, and synchronous renderResults and reportError callbacks. Pass signal to fetch, check HTTP status and validate data. dispose removes the listener and cancels both pending and active work. Stale results are ignored even if the data layer ignores cancellation. [17]
When to move work to a Web Worker
Main-thread code (filter.mjs)
export function filterInWorker(records, query, { signal } = {}) {
return new Promise((resolve, reject) => {
signal?.throwIfAborted();
const worker = new Worker(new URL("./filter.worker.js", import.meta.url), {
type: "module",
});
function cleanup() {
signal?.removeEventListener("abort", handleAbort);
worker.terminate();
}
function fail(error) {
cleanup();
reject(error);
}
function handleAbort() {
fail(signal.reason);
}
worker.addEventListener("message", ({ data }) => {
cleanup();
resolve(data);
});
worker.addEventListener("error", (event) => {
event.preventDefault();
fail(new Error(event.message || "The filter worker failed."));
});
worker.addEventListener("messageerror", () => {
fail(new Error("The worker response could not be decoded."));
});
signal?.addEventListener("abort", handleAbort, { once: true });
try {
worker.postMessage({ records, query });
} catch (error) {
fail(error);
}
});
}Worker code (filter.worker.js)
self.addEventListener("message", ({ data }) => {
const { records, query } = data;
const normalizedQuery = query.trim().toLowerCase();
const results = records.filter((record) =>
record.name.toLowerCase().includes(normalizedQuery),
);
self.postMessage(results);
});
Web Workers execute JavaScript on a background thread so CPU-heavy computation does not occupy the UI thread. MDN recommends them for expensive work that can be separated from direct DOM access. [11]
Workers cannot manipulate the DOM directly. Data is exchanged with postMessage(), and large buffers can use transferable objects to avoid expensive copies. [11]
Good candidates include large-data parsing, search, compression, geometry, image processing and ranking algorithms. A tiny DOM handler should not be moved to a worker merely for architectural purity.
Save the modules as filter.mjs and filter.worker.js in the same directory and serve them over HTTP(S). Pass validated records with a name field and a query string. Handle Promise rejection and abort the previous call via AbortController. A worker terminates after each result or error; for frequent calls consider reuse, accounting for startup and cloning costs. [16]
Rendering can also ruin INP: layout thrashing and large DOMs
High presentation delay means event handlers may already be finished while the browser is still spending time in style, layout or paint. web.dev points to large DOMs and layout thrashing as common causes. [2]
Chrome describes using Long Animation Frames data to separate style recalculation and layout costs. Forced style and forced layout can reveal scripts that mutate DOM and then immediately read geometry, forcing synchronous rendering work. [8]
Typical fixes include batching DOM reads before writes, reducing the scope of updates and avoiding rebuilding large UI subtrees for small state changes.
Long Tasks versus Long Animation Frames
Simple Long Tasks observer (observe.mjs)
export function observePerformance(type, report, options = {}) {
const Observer = globalThis.PerformanceObserver;
if (!Observer?.supportedEntryTypes?.includes(type)) {
return null;
}
const observer = new Observer((list) => {
for (const entry of list.getEntries()) {
report(entry);
}
});
observer.observe({ ...options, type, buffered: true });
return function dispose() {
observer.disconnect();
};
}
// Local diagnostics; do not transmit raw attribution data.
export function observeLongTasks(report) {
return observePerformance("longtask", (entry) => {
report({ duration: entry.duration });
});
}Long Animation Frames observer (loaf.mjs)
import { observePerformance } from "./observe.mjs";
export function observeLongFrames(report) {
return observePerformance("long-animation-frame", (frame) => {
report({
duration: frame.duration,
blockingDuration: frame.blockingDuration,
scriptCount: frame.scripts.length,
});
});
}
The Long Tasks API reports UI-thread tasks lasting at least 50 ms, but MDN marks PerformanceLongTaskTiming as limited availability and non-standard. [6]
The Long Animation Frames API looks at the whole slow frame, which can include several shorter tasks plus rendering, and provides richer attribution for scripts, style and layout. [7]
For new telemetry, LoAF is a useful additional diagnostic where supported, while Long Tasks remains a simpler blocking signal.
Save the first block as observe.mjs and the second as loaf.mjs. Supply a lightweight synchronous report callback; null means the entry type is unsupported, otherwise call the returned function to disconnect. Do not transmit raw script attribution without a privacy review. [15]
Measure interactions, not only tasks
Diagnostic Event Timing subparts (event.mjs)
import { observePerformance } from "./observe.mjs";
const EVENT_DURATION_THRESHOLD_MS = 40;
export function observeInteractionEvents(report) {
return observePerformance(
"event",
(entry) => {
if (!entry.interactionId) {
return;
}
const inputDelay = entry.processingStart - entry.startTime;
const processingDuration = entry.processingEnd - entry.processingStart;
// Event duration is rounded to 8 ms; the residual is approximate.
const presentationDelay = Math.max(
0,
entry.duration - inputDelay - processingDuration,
);
report({
name: entry.name,
interactionId: entry.interactionId,
duration: entry.duration,
inputDelay,
processingDuration,
presentationDelay,
});
},
{ durationThreshold: EVENT_DURATION_THRESHOLD_MS },
);
}
The Event Timing API exposes PerformanceEventTiming, including startTime, processingStart, processingEnd, duration and interactionId. This lets you inspect how long an event waited and how long callback processing took. [13]
Event entries are exposed for slower events by default and durationThreshold can lower the observation threshold. Calculating full INP correctly has several nuances, so Chrome recommends a RUM solution or the web-vitals library rather than a simplified custom implementation. [8][13]
The example below is a diagnostic tool for individual events, not a complete INP implementation.
Save this module as event.mjs alongside observe.mjs. Event duration is rounded to 8 ms; the residual is approximate, and clamping to zero removes negative rounding artifacts. Do not aggregate these entries into an INP metric. [13][15]
Field data, CrUX, RUM and DevTools
| Measurement layer | What it provides | Limitation |
|---|---|---|
| CrUX / PageSpeed Insights | Real-user INP at URL or origin level | Limited root-cause detail |
| RUM | Interaction, context, subparts, device | Requires telemetry and analysis |
| DevTools Performance | Detailed main-thread trace | Lab environment, must reproduce issue |
| TBT | Lab signal of load-time blocking | Not a replacement for INP |
web.dev recommends starting with field data because INP depends on real interactions, devices and timing. CrUX in PageSpeed Insights can show whether a problem exists but usually cannot identify the exact handler. [1][2]
RUM can attribute poor responsiveness to a concrete interaction and collect subparts. Chrome recommends web-vitals/attribution when no other RUM solution exists because it can include Long Animation Frames attribution. [8]
In the lab, reproduce real user flows in the Performance panel, especially interactions during page load when the main thread is often busiest. [2][14]
A practical INP improvement workflow
Start by finding genuinely slow interactions in field data. Reproduce them in the lab and identify whether input delay, processing duration or presentation delay dominates. Do not begin by randomly adding timeouts or workers.
If the main thread is busy before interaction, reduce startup JavaScript, timers and third-party work. If the handler itself is expensive, remove or split work. If presentation delay dominates, profile style, layout, DOM and paint. Move only CPU-heavy DOM-independent computation to workers.
- Measure field INP at the 75th percentile and identify concrete slow interactions.
- Split diagnosis into input delay, processing duration and presentation delay.
- Remove unnecessary JavaScript before introducing schedulers.
- Show minimal UI feedback before heavy work.
- Chunk long work at sensible boundaries and feature-detect
scheduler.yield(). - Do not use
Promise.then()orqueueMicrotask()as rendering-yield substitutes. - Move CPU-heavy, DOM-independent work to Web Workers.
- After each change, recheck field data and the trace of the specific interaction.
