Course contentsShow
← Web Development
Lesson 1922 of 2,98235. Web Performance FundamentalsFree lesson

Long Tasks API

Detect tasks blocking the main thread for more than 50ms using Long Tasks API.

Long Tasks API

What you'll learn: How to use the Long Tasks API to detect JavaScript tasks that block the main thread for more than 50ms, helping you pinpoint performance bottlenecks.

The Main Thread Bottleneck Problem

Your browser's main thread is like a single cashier at a busy store — it can only handle one customer (task) at a time. When a JavaScript task takes longer than 50ms, it creates a noticeable "long task" that blocks everything else: user interactions freeze, animations stutter, and your site feels sluggish. The Long Tasks API automatically flags these problem tasks.

How the Long Tasks API Works

This API uses the PerformanceObserver (which you learned about) to monitor tasks. Any JavaScript execution, rendering, or layout work that exceeds the 50ms threshold triggers an entry you can capture and analyze:

// Create an observer for 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,
      attribution: entry.attribution
    });
  }
});

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

The attribution property can even tell you which script or frame caused the long task, though browser support varies. This information is invaluable for debugging performance issues that affect FID (First Input Delay) and INP (Interaction to Next Paint).

Why 50ms Matters

To maintain 60 frames per second, you have ~16ms per frame. A 50ms task consumes three frames, creating visible jank and unresponsive UI.

Key Takeaway: The Long Tasks API automatically surfaces JavaScript work exceeding 50ms, giving you visibility into main thread blockages that hurt interactivity metrics — use PerformanceObserver with entryTypes: ['longtask'] to catch them.