Course contentsShow
← JavaScript
Lesson 2192 of 2,72345. Workers and ConcurrencyFree lesson

Measuring Task Duration with Performance APIs

Use performance.now() and the Long Tasks API to identify operations that justify worker offloading.

Measuring Task Duration with Performance APIs

You'll learn how to use performance.now() and the Long Tasks API to measure operations and decide which ones need worker offloading.

Why Measurement Matters

Before moving expensive work to a worker thread, you need evidence that the work actually blocks the main thread long enough to hurt user experience. Guessing wastes time—measurement tells you exactly where the bottlenecks are.

Using performance.now()

The performance.now() method returns a high-resolution timestamp in milliseconds. Wrap any synchronous operation to measure its duration:

const start = performance.now();

// Your CPU-intensive operation
for (let i = 0; i < 10000000; i++) {
  Math.sqrt(i);
}

const end = performance.now();
console.log(`Operation took ${end - start}ms`);

Rule of thumb: Tasks taking more than 50ms risk causing dropped frames (at 60 FPS, each frame has ~16ms). These are prime candidates for worker offloading.

The Long Tasks API

The Long Tasks API automatically detects tasks exceeding 50ms:

const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log(`Long task detected: ${entry.duration}ms`);
    // This operation should probably move to a worker
  }
});

observer.observe({ entryTypes: ['longtask'] });

This passive monitoring catches blocking operations you might not even know exist—user interactions, third-party scripts, or complex calculations.

Making the Decision

If performance.now() shows a task consistently exceeds 50ms, or if Long Tasks Observer flags it, that's your signal: this work justifies the overhead of worker communication.

Key Takeaway: Use performance.now() for targeted measurements and the Long Tasks API for passive monitoring—both reveal which operations block the main thread long enough to warrant worker offloading.