Optimizing Long Tasks for Improved Site Responsiveness
Imagine a user clicks a button, and the interface freezes for half a second. That's a Long Task — a main thread task longer than 50 ms. INP (Interaction to Next Paint) — a Core Web Vitals metric — directly suffers from such tasks. According to Interaction to Next Paint (INP), delays over 200 ms can reduce conversion by up to 3%. Our team specializes in identifying and eliminating Long Tasks in complex SPAs. In 5 years, we've optimized over 30 projects, achieving INP reductions from >500 ms to <200 ms. Clients report increased engagement and reduced bounce rates after optimization. Additionally, reducing TBT (Total Blocking Time) directly saves server resources and lowers maintenance costs.
Why Long Tasks Block the Interface
Any Long Task longer than 50 ms blocks user input processing: clicks, scrolls, key presses. INP captures the worst response delay for interactions. Eliminating Long Tasks is a direct path to improving Core Web Vitals and boosting conversions. We guarantee at least a 30% INP improvement after optimization.
How to Find Long Tasks in Production
Open Chrome DevTools → Performance tab → start recording → simulate load or interaction → stop. On the Main track, red triangles mark tasks longer than 50 ms. Click a task — the call tree below shows which functions were called and how long each took. Key metrics: Total Blocking Time (sum of (duration - 50ms) over all Long Tasks), fractions of Scripting, Rendering, Painting.
For production profiling, use PerformanceObserver. It sends Long Task data to the server for analysis. Here's an example:
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
navigator.sendBeacon('/api/longtasks', JSON.stringify({
duration: entry.duration,
startTime: entry.startTime,
url: location.href,
userAgent: navigator.userAgent,
}));
}
});
observer.observe({ type: 'longtask', buffered: true });
Tools for Finding Long Tasks
- Chrome DevTools: Performance tab, Main track, colored bars.
- PerformanceObserver in production for field data collection.
- web-vitals library to measure INP in real-world conditions.
How to Eliminate a Long Task: Method Overview
| Method | Browser Support | Rescheduling Delay | Convenience |
|---|---|---|---|
setTimeout(fn, 0) |
All | Minimum 4 ms | Requires manual chunking |
scheduler.yield() |
Chrome 115+, Edge 115+ | ~0 ms (prioritized) | Built-in yield |
requestIdleCallback |
Most mobile & desktop | Adaptive | Non-critical only |
scheduler.yield() provides minimal delay and automatically yields control upon input events. It is 2–5× more efficient than setTimeout due to interaction prioritization.
Practical Optimization Patterns
How to Chunk a Task with scheduler.yield()
The most direct way to eliminate a Long Task is to break it into parts and yield control between parts. Modern approach 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();
}
}
}
A polyfill for browsers without scheduler.yield() uses MessageChannel — delay ~0 ms.
Why Offload Computations to Web Workers?
Heavy computations that don't work with the DOM (JSON parsing, cryptography, complex sorts) should be moved to Workers. Example WorkerPool:
// main.js
class WorkerPool {
constructor(workerScript, poolSize = navigator.hardwareConcurrency || 4) {
this.workers = Array.from({ length: poolSize }, () => new Worker(workerScript));
this.queue = [];
this.available = [...this.workers];
}
run(type, payload) {
return new Promise((resolve, reject) => {
const task = { type, payload, resolve, reject };
if (this.available.length > 0) {
this._dispatch(task);
} else {
this.queue.push(task);
}
});
}
_dispatch({ type, payload, resolve, reject }, worker = this.available.pop()) {
worker.onmessage = ({ data }) => {
resolve(data.result);
this.available.push(worker);
if (this.queue.length > 0) this._dispatch(this.queue.shift());
};
worker.onerror = reject;
worker.postMessage({ type, payload });
}
}
const pool = new WorkerPool('/heavy-worker.js', 2);
const sortedProducts = await pool.run('SORT_PRODUCTS', products);
React: startTransition and useDeferredValue
React 18 allows explicit distinction between urgent and non-urgent updates. startTransition for non-critical state updates:
import { startTransition, useState } from 'react';
function SearchPage() {
const [inputValue, setInputValue] = useState('');
const [searchQuery, setSearchQuery] = useState('');
function handleInput(e) {
const value = e.target.value;
setInputValue(value);
startTransition(() => setSearchQuery(value));
}
return (
<>
<input value={inputValue} onChange={handleInput} />
<SearchResults query={searchQuery} />
</>
);
}
useDeferredValue for lists: defers filter updates.
How Virtual List Rendering Accelerates Rendering?
Rendering thousands of DOM elements creates one big Long Task. Virtualization renders only visible elements. Example 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 Results
Before and after optimization, measure in lab conditions (Lighthouse, 4× CPU throttle, 3G) and in the field (INP via web-vitals). Typical results:
| Metric | Before Optimization | After Optimization |
|---|---|---|
| TBT | 1–3 s | <300 ms |
| INP | 400–600 ms | <200 ms |
At least 30% INP improvement — confirmed by experience across 30+ projects.
What the Work Includes and Timelines
- Profiling audit: collect Long Tasks via DevTools and production monitoring, analyze call stack. (2–3 days)
- Code splitting and chunking: split large chunks, lazy load modules.
- Offload heavy computations to Web Workers with a WorkerPool.
- Virtualize long lists using react-virtual or similar.
- Optimize React components: startTransition, useDeferredValue, memoization.
- Re-measure and report: compare INP/TBT before and after, recommendations.
Full optimization cycle for a complex SPA — 2–4 weeks. For simpler sites with server-side rendering — 3–7 days.
How Long Does Optimization Take?
Diagnosis: 2–3 days; full cycle: 2–4 weeks for SPA, 3–7 days for simpler sites. Cost is calculated individually.
Request a Long Task audit — get a report with recommendations and a plan. Contact us to start improving your site's responsiveness today.







