Run With a Performance Budget (Sync or Async)

intermediate
By FrontendAtlas Editorial · Updated Oct 10, 2026
Implement runWithPerfBudget(fn, budgetMs, now?) to time a sync or async function and report whether it stayed within a budget. This mirrors how teams add perf budgets in CI and how you reason about long tasks ("why is this >16ms?") in profiling sessions.

Arguments

  • fn: Function — The operation to run. Can return a value or a Promise.
  • budgetMs: number — Budget in milliseconds (>= 0).
  • now: () => number (optional) — Time source for testability. Defaults to performance.now() when available, else Date.now().

Returns

Promise<{ ok: boolean, durationMs: number, value: any }> — Whether the run stayed within budget, measured duration, and the resolved value.

Solution idea

Measure time before and after running fn. If fn returns a Promise, await it before taking the end timestamp. Use an injectable now() so tests are deterministic.

Examples
await runWithPerfBudget(() => expensiveWork(), 16)
// => { ok: false, durationMs: 42, value: ... }

await runWithPerfBudget(async () => await doFetchLikeWork(), 200)
// => { ok: true, durationMs: 120, value: ... }