实现说明
循环只出现在 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);