← 中文资源

简体中文版本

PerformanceObserver 收集计时条目

PerformanceObserver 用回调推送 mark/measure 条目,entryTypes 声明只关心哪几类;数据是异步送达的,回调里收好再 disconnect。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

循环只出现在 for (const entry of list.getEntries()),它的每次迭代处理一个元素。异步流被 await 线性化,失败处理保持局部。 演示用的数据放在这几个模块级绑定中:entries、observer、span。

使用要点

  • 跑完文件,输出里会留下标记——entries:、measured directly:、entry count:。

常见问题

复制和运行之间有安装步骤吗?

没有。从复制到运行之间没有别的要做。 文件的状态由几个模块级绑定持有:entries、observer、span。

核心语句

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);
  }
});

代码示例

// 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);