Course contentsShow
← Web Development
Lesson 1986 of 2,98236. Performance Optimization TechniquesFree lesson

Identifying Long Tasks with Performance API

Use PerformanceObserver and the Long Tasks API to detect tasks blocking the main thread for more than 50ms.

Identifying Long Tasks with Performance API

You'll learn how to detect JavaScript tasks that block the main thread for more than 50ms using the Performance API.

What Are Long Tasks?

A "long task" is any JavaScript execution or rendering work that monopolizes the main thread for 50 milliseconds or longer. During this time, the browser can't respond to user input—clicks feel sluggish, scrolling stutters, and your site feels janky. Think of it like a single customer taking forever at a checkout counter while everyone else waits impatiently in line.

Using PerformanceObserver with Long Tasks API

The Long Tasks API gives you visibility into these blocking tasks. You observe them using PerformanceObserver:

// Create an observer that watches for long tasks
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log('Long task detected!');
    console.log('Duration:', entry.duration, 'ms');
    console.log('Start time:', entry.startTime);
    console.log('Attribution:', entry.attribution);
  }
});

// Start observing longtask entries
observer.observe({ entryTypes: ['longtask'] });

Each detected entry includes:

  • duration: How long the task ran (always ≥ 50ms)
  • startTime: When it began
  • attribution: Context about what caused it (often limited for security)

Why This Matters

Long tasks directly harm FID and INP metrics. By identifying them, you can pinpoint which scripts or operations need optimization—whether that's breaking work into smaller chunks, deferring non-critical code, or offloading to Web Workers.

Key Takeaway: Use PerformanceObserver with entryTypes: ['longtask'] to automatically detect main-thread-blocking tasks over 50ms, helping you diagnose and fix responsiveness issues.