What is a long task, and how do you keep the main thread responsive?
AdvancedPerformance interview questionBy UIRound, updated 17 November 2026
Short answer
A long task is any task that keeps the browser's main thread busy for more than 50 milliseconds. While it runs, the browser cannot respond to clicks, key presses or paint, so the page feels frozen and Interaction to Next Paint (INP) gets worse. You keep the main thread responsive by breaking work into smaller chunks that yield between them, moving heavy computation to a Web Worker, and doing less work per interaction.
Why 50 milliseconds
The main thread runs one task at a time: a script, an event handler, a timer callback, a parse step. It can only handle input and render a frame between tasks. Responses that arrive within about 100 ms feel instant to people. If tasks are capped at 50 ms, an input that arrives at the worst moment waits at most 50 ms, leaving the other half of the budget for running the handler and painting. Anything past 50 ms is counted as "blocking time", which is what Total Blocking Time in Lighthouse adds up. The way tasks, microtasks and rendering take turns is described in the event loop guide.
How long tasks hurt INP
INP measures the time from a user's interaction to the next frame painted after it, and reports roughly the worst one on the page. That time has three parts, and long tasks can inflate each:
- Input delay: an unrelated long task (a third-party script, hydration) is already running when the user clicks.
- Processing time: your own event handler does too much work.
- Presentation delay: the update is so large that style, layout and paint take a long time.
See Core Web Vitals for the thresholds.
Finding long tasks
- Performance panel. Record while you reproduce the slow interaction, with CPU throttling on. Long tasks have a red triangle in the corner in the Main track; expand one to see which functions take the time. The Interactions track shows each interaction split into its three phases.
- In the field. A
PerformanceObservercan watchlongtaskentries, or, in Chromium browsers,long-animation-frameentries, which also attribute the time to the scripts that caused it:
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log(entry.duration, entry.scripts?.map((s) => s.sourceURL));
}
}).observe({ type: "long-animation-frame", buffered: true });Lab tests on a fast laptop often miss the problem; field data from real devices finds it.
Yielding: break one long task into many short ones
If a loop processes 10,000 items in one go, it is one long task. Yielding means pausing every few milliseconds so the browser can handle input and paint, then continuing in a new task.
function yieldToMain() {
if (globalThis.scheduler?.yield) return scheduler.yield();
return new Promise((resolve) => setTimeout(resolve, 0));
}
async function processAll(items, handle) {
let deadline = performance.now() + 30; // stay well under 50 ms per chunk
for (const item of items) {
handle(item);
if (performance.now() >= deadline) {
await yieldToMain();
deadline = performance.now() + 30;
}
}
}scheduler.yield() is supported in Chromium-based browsers but not everywhere yet, hence the feature check. Its advantage is that the continuation goes to the front of the queue, so other scripts cannot jump in and make your work take much longer. The setTimeout fallback puts the continuation at the back of the task queue and is clamped to at least about 4 ms after several nested calls, but it still lets input and rendering through. Awaiting a resolved promise does not yield, because microtasks run before the browser gets a chance to render.
Yield inside event handlers
Do the work the user sees first, yield, then do the rest:
saveButton.addEventListener("click", async () => {
showSavedState(); // visible change, painted on the next frame
await yieldToMain();
sendAnalytics(); // not urgent
syncOtherTabs();
});This alone often fixes a poor INP, because the frame is painted before the slow, invisible work runs.
Other ways to do less on the main thread
- Web Workers. Parsing large files, searching, image processing and other pure computation can run on another thread; see Web Workers. The cost is copying data in and out with
postMessage, so send compact data or transfer buffers. - Debounce or throttle input. Filtering a list on every keystroke can be cut to one run after the user pauses. The debounce vs throttle guide compares both.
- Render less. Virtualise long lists (list virtualization), avoid layout thrashing (reflow vs repaint) and skip re-rendering components that did not change.
- Let React schedule it.
startTransitionmarks an update as non-urgent so React renders it in interruptible slices and keeps typing responsive; see the useTransition guide. - Defer third-party scripts and split large hydration work, which are common sources of input delay on load.
Practise it
Write the yielding loop in Split a long task into chunks that yield to the browser, then debug a real case in Investigate an INP of 600 ms in the field. Build a time-sliced task runner with priority lanes, Implement a Web Worker for CPU-intensive computation and Build a worker pool for fuzzy search go further.
Common follow-up questions
Does making a function async stop it from blocking?
No. An async function runs synchronously until its first await, and code after an await on a resolved promise runs as a microtask before the browser renders. Only work that is split across separate tasks, or moved to another thread, gives the browser a chance to respond.
What about requestIdleCallback?
It runs a callback when the browser has idle time, which suits low-priority work such as prefetching or analytics. It is not supported in every browser, and idle time may never come on a busy page, so give it a timeout and a fallback.
How small should each chunk be?
Small enough to stay well under 50 ms on a slow phone, not a fast laptop. Yielding has overhead, so checking the elapsed time and yielding every few milliseconds of work is better than yielding after every item.
What is the difference between a long task and a long animation frame?
A long task is one task over 50 ms. A long animation frame is a frame whose rendering was delayed past 50 ms, which may involve several tasks plus style and layout work. The newer Long Animation Frames API reports the latter, with attribution to scripts, which matches what users feel more closely.
Mistakes to avoid
Testing only on a fast machine without CPU throttling
Thinking
async/awaitor promises make heavy work non-blockingYielding after every single item, so overhead dominates
Doing analytics, logging and other invisible work before the visible update in a handler
Sending huge objects to a worker on every message, so copying costs more than the work
Ignoring third-party scripts, which often cause the input delay
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Split a long task into chunks that yield to the browser to keep INP lowMedium30 min
- Investigate an INP of 600 ms in the field that looks fine in the labHard45 min
- Build a time-sliced task runner with priority lanes, cancellation and starvation protectionHard60 min
- Implement a Web Worker for CPU-intensive computationMedium40 min
- Build a worker pool for fuzzy search: idle routing, a queue, latest-query-wins and transferablesHard50 min