PerformanceObserver Watches Timing Entries

PerformanceObserver collects mark and measure entries through a callback with entryTypes filtering, so timing data arrives instead of being polled manually.

JavascriptCli Tooling

Code

snippet
// PerformanceObserver delivers timing entries through a callback instead of
// polling performance.now around every step.
const entries = [];

const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    entries.push(entry.name + ' [' + entry.entryType + '] ' + entry.duration);
  }
});
observer.observe({ entryTypes: ['mark', 'measure'] });

performance.mark('build-start');
performance.mark('build-end');
const span = performance.measure('build', 'build-start', 'build-end');

// Delivery is asynchronous: give the observer task a chance to run
await new Promise((resolve) => setTimeout(resolve, 25));
observer.disconnect();

console.log('entries:', entries.join(' | '));
console.log('measured directly:', span.duration);
console.log('entry count:', entries.length);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

entries: build-start [mark] 0 | build [measure] 0.1997 | build-end [mark] 0
measured directly: 0.1997
entry count: 3

How it works

Repetition is confined to for (const entry of list.getEntries()) — the rest of the file is straight-line. The asynchronous flow is linearized with await, keeping failure handling local.

Top-level bindings entries, observer, span hold the demo state — nothing sits inside a function scope.

Using it

The demo output is labeled (entries:, measured directly:, entry count:); each label names the call that printed it.

Key statements

await new Promise((resolve) => setTimeout(resolve, 25));
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    entries.push(entry.name + ' [' + entry.entryType + '] ' + entry.duration);
  }
});

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. Its state lives in module-level bindings: `entries`, `observer`, `span`.