Course contentsShow
← JavaScript
Lesson 1922 of 2,72340. PerformanceFree lesson

The Performance Observer API

Listening to performance entries asynchronously to collect timing data without blocking execution.

The Performance Observer API

What you'll learn: How to monitor performance metrics asynchronously without blocking your application's execution flow.

Why Observers Instead of Direct Queries?

Until now, you've been pulling performance data — calling performance.getEntriesByType() at specific moments. The Performance Observer API flips this around: it pushes performance entries to you as they happen, letting you collect timing data without constantly checking or blocking the main thread.

Think of it like subscribing to a news feed instead of refreshing a webpage every minute. The browser notifies you when new performance entries are recorded, and you handle them asynchronously.

How It Works

Create a PerformanceObserver with a callback function that receives performance entries. Then tell it which entry types to watch:

const observer = new PerformanceObserver((list) => {
  const entries = list.getEntries();
  entries.forEach(entry => {
    console.log(`${entry.name}: ${entry.duration}ms`);
  });
});

// Start observing specific entry types
observer.observe({ entryTypes: ['measure', 'navigation'] });

// Now create marks and measures
performance.mark('start-task');
// ...do work...
performance.mark('end-task');
performance.measure('task-duration', 'start-task', 'end-task');
// Observer automatically receives the measure!

Benefits

The observer is non-blocking — your callback runs after the performance entry is created, but doesn't interrupt the critical execution path. You can collect detailed metrics in production without worrying about the measurement code itself slowing things down.

You can stop observing with observer.disconnect() when you no longer need data.

Key Takeaway: The Performance Observer API lets you monitor performance metrics asynchronously through a callback-based subscription model, avoiding the overhead and timing issues of manual polling.