Optimizing Long Tasks for Improved Responsiveness
Long Task is any task on main thread browser execution taking more than 50 milliseconds. While Long Task executes, browser can't process user input: click, scroll, key press. User sees "frozen" interface. 50 ms is perception threshold: delays below 50 ms unnoticed, everything above already "sluggish".
Long Tasks are root cause of poor TTI, TBT and INP. Understanding what causes them—not quick work. No single magic trick.
Diagnosis: Profiling in Chrome DevTools
DevTools → Performance → start recording → simulate load or interaction → stop.
On Main track see red triangles on tasks longer than 50 ms. Click task—call tree appears in bottom panel: which functions called and how long each took.
For production profiling without DevTools:
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log({
duration: entry.duration,
startTime: entry.startTime,
attributions: entry.attribution?.map(a => ({
containerType: a.containerType,
containerSrc: a.containerSrc,
name: a.name,
})),
});
navigator.sendBeacon('/api/longtasks', JSON.stringify({
duration: entry.duration,
startTime: entry.startTime,
url: location.href,
userAgent: navigator.userAgent,
}));
}
});
observer.observe({ type: 'longtask', buffered: true });
Pattern 1: Task Chunking with scheduler.yield()
Most direct way—split task into parts, yield to browser between parts.
Old way via setTimeout(0):
function processLargeArray(items) {
const CHUNK_SIZE = 100;
let index = 0;
function processChunk() {
const end = Math.min(index + CHUNK_SIZE, items.length);
for (let i = index; i < end; i++) {
processItem(items[i]);
}
index = end;
if (index < items.length) {
setTimeout(processChunk, 0);
}
}
processChunk();
}
Modern way via scheduler.yield() (Chrome 115+):
async function processLargeArrayModern(items) {
const CHUNK_SIZE = 100;
for (let i = 0; i < items.length; i += CHUNK_SIZE) {
const chunk = items.slice(i, i + CHUNK_SIZE);
chunk.forEach(processItem);
if (i + CHUNK_SIZE < items.length) {
await scheduler.yield();
}
}
}
Polyfill for browsers without scheduler.yield():
function yieldToMain() {
if ('scheduler' in self && 'yield' in scheduler) {
return scheduler.yield();
}
return new Promise(resolve => {
const channel = new MessageChannel();
channel.port1.onmessage = resolve;
channel.port2.postMessage(undefined);
});
}
Pattern 2: Web Workers for CPU-Intensive Work
Move work not touching DOM to Worker. Typical candidates: parsing large JSON, crypto, complex filters, file processing.
// heavy-worker.js
self.onmessage = function({ data: { type, payload } }) {
let result;
switch (type) {
case 'SORT_PRODUCTS':
result = payload.sort((a, b) => complexSort(a, b));
break;
case 'PARSE_CSV':
result = parseCSV(payload);
break;
}
self.postMessage({ type: type + '_DONE', result });
};
// main.js
const worker = new Worker('/heavy-worker.js');
worker.postMessage({ data: largeArray, operation: 'sort' });
worker.onmessage = (e) => setTableData(e.data);
Pattern 3: requestIdleCallback for Non-Critical Work
Schedule analytics, preloading, state saving for browser idle time:
function scheduleNonCritical(work) {
if ('requestIdleCallback' in window) {
requestIdleCallback((deadline) => {
while (deadline.timeRemaining() > 0 && work.length > 0) {
const task = work.shift();
task();
}
if (work.length > 0) {
scheduleNonCritical(work);
}
}, { timeout: 2000 });
} else {
setTimeout(() => work.forEach(t => t()), 1);
}
}
Pattern 4: React 18 — startTransition and useDeferredValue
React 18 added mechanism for explicit urgent vs non-urgent updates.
startTransition for non-urgent updates:
function SearchPage() {
const [inputValue, setInputValue] = useState('');
const [searchQuery, setSearchQuery] = useState('');
function handleInput(e) {
const value = e.target.value;
setInputValue(value); // Urgent
startTransition(() => {
setSearchQuery(value); // Non-urgent
});
}
return (
<>
<input value={inputValue} onChange={handleInput} />
<SearchResults query={searchQuery} />
</>
);
}
useDeferredValue for lists:
const MemoizedList = memo(function ExpensiveList({ items, filter }) {
const filtered = items.filter(item => matchesComplexFilter(item, filter));
return <div>{filtered.map(item => <Item key={item.id} {...item} />)}</div>;
});
function FilteredCatalog({ products, filter }) {
const deferredFilter = useDeferredValue(filter);
const isStale = filter !== deferredFilter;
return (
<div style={{ opacity: isStale ? 0.7 : 1 }}>
<MemoizedList items={products} filter={deferredFilter} />
</div>
);
}
Pattern 5: Virtualizing Long Lists
Rendering thousands of DOM elements—one big Long Task. Virtualization renders only visible elements.
With @tanstack/react-virtual:
import { useVirtualizer } from '@tanstack/react-virtual';
function VirtualList({ items }) {
const parentRef = useRef(null);
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 72,
overscan: 5,
});
return (
<div ref={parentRef} style={{ height: '600px', overflow: 'auto' }}>
<div style={{ height: virtualizer.getTotalSize() }}>
{virtualizer.getVirtualItems().map(virtualItem => (
<div
key={virtualItem.key}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
transform: `translateY(${virtualItem.start}px)`,
}}
>
<ListItem item={items[virtualItem.index]} />
</div>
))}
</div>
</div>
);
}
Measuring Result
Before and after lab conditions (Lighthouse, 4× CPU throttle, 3G) and field (INP via web-vitals):
import { onINP } from 'web-vitals/attribution';
onINP(({ value, attribution }) => {
const { interactionType, interactionTarget, processingStart, processingEnd } = attribution;
console.log({
inp: value,
interaction: interactionType,
processingTime: processingEnd - processingStart,
});
});
Typical after full optimization: TBT drops from 1–3 seconds to < 300 ms, INP improves from 400–600 ms to < 200 ms.
Timeframe
Diagnosis of Long Tasks via DevTools + production profiling — 2–3 business days. Full cycle: code splitting, Web Workers, React transitions, virtualization — 2–4 weeks for complex SPA. Simple sites with mostly server rendering — 3–7 business days.







