Long Tasks >50ms Blocking Main Thread Fix
In this tutorial, you'll learn about Long Tasks >50ms Blocking Main Thread Fix. We cover key concepts, practical examples, and best practices.
The Problem
A "long task" is any JavaScript task that executes on the main thread for more than 50 milliseconds. These block user interactions, cause input delay, and degrade Interaction to Next Paint (INP) scores. Long tasks are visible in Chrome DevTools as red triangles in the Performance panel.
Quick Fix
Step 1: Identify long tasks
// Wrong — no visibility into main thread blocking
function processData(data) {
const results = [];
for (let i = 0; i < data.length; i++) {
results.push(expensiveOperation(data[i]));
}
return results;
}
// Right — use PerformanceObserver to detect long tasks
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.warn('Long task detected:', {
duration: entry.duration,
startTime: entry.startTime,
name: entry.name
});
}
});
observer.observe({ entryTypes: ['longtask'] });
Step 2: Break up long tasks with setTimeout
// Wrong — single long task blocks the main thread
function processAll(items) {
items.forEach(item => {
heavyComputation(item);
});
}
// Right — yield to the main thread periodically
function processAll(items, index = 0) {
if (index >= items.length) return;
const BATCH_SIZE = 50;
const end = Math.min(index + BATCH_SIZE, items.length);
for (let i = index; i < end; i++) {
heavyComputation(items[i]);
}
// Yield to the main thread before processing the next batch
setTimeout(() => processAll(items, end), 0);
}
Step 3: Use scheduler.postTask for prioritization
// Wrong — no way to express priority
executeHeavyTask();
// Right — use Scheduler API for task prioritization
if ('scheduler' in window) {
scheduler.postTask(() => {
executeHeavyTask();
}, { priority: 'background' });
} else {
// Fallback for browsers without Scheduler API
setTimeout(() => executeHeavyTask(), 0);
}
Step 4: Use requestIdleCallback for non-urgent work
// Wrong — non-urgent work runs immediately
analyticsTracker.sendAllPending();
// Right — run during idle time
if ('requestIdleCallback' in window) {
requestIdleCallback((deadline) => {
while (deadline.timeRemaining() > 0 && queue.length > 0) {
const item = queue.shift();
analyticsTracker.send(item);
}
if (queue.length > 0) {
requestIdleCallback(/* re-queue */);
}
}, { timeout: 2000 });
}
Step 5: Defer parsing with async and defer
<!-- Wrong — script blocks parsing -->
<script src="heavy-script.js"></script>
<!-- Right — defer for dependencies, async for independent -->
<script defer src="heavy-script.js"></script>
<script async src="analytics.js"></script>
Prevention
- Keep tasks under 50ms — split any task that exceeds this
- Use PerformanceObserver to monitor long tasks in production
- Batch DOM reads and writes separately to avoid layout thrashing
- Use Web Workers for CPU-intensive computation
- Prioritize user-visible work with
scheduler.postTask
Common Mistakes with long tasks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world PERF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro