doc: main `perf_hooks` example throws when async

📗 API Reference Docs Problem

  • Version: v16.12.0
  • Platform: Darwin Martins-MBP.lan 20.6.0 Darwin Kernel Version 20.6.0: Mon Aug 30 06:12:21 PDT 2021; root:xnu-7195.141.6~3/RELEASE_X86_64 x86_64
  • Subsystem: perf_hooks

Location

Section of the site where the content exists

Affected URL(s):

Description

Concise explanation of the problem

Simply defining

const doSomeLongRunningProcess = (cb) => global.setTimeout(cb, 1e3)

will make the example throw.

The available fixes are, to my knowledge

  1. make doSomeLongRunningProcess sync (e.g. const doSomeLongRunningProcess = (f) => f())
  2. remove performance.measure('Start to Now')
  3. remove performance.clearMarks()

I think the proper solution is 3.

Additionally, the performance observer only emits the first entry.

A more proper example would be the following, as it handles the edge cases gracefully:

const { PerformanceObserver, performance } = require('perf_hooks');

const obs = new PerformanceObserver((items) => {
  console.log(
    items.getEntries().map(({ name, duration }) => `${name}: ${duration}`),
  )
})
obs.observe({ type: 'measure' })
performance.measure('Start to Now')

performance.mark('A')
// const doSomeLongRunningProcess = (cb) => setTimeout(cb, 1e3)
// const doSomeLongRunningProcess = (cb) => cb()
doSomeLongRunningProcess(() => {
  performance.measure('A to Now', 'A')

  performance.mark('B')
  performance.measure('A to B', 'A', 'B')
  
  performance.clearMarks();
})

  • I would like to work on this issue and
    submit a pull request.