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.
Code
// 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: 3How 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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.