closeout
API reference

closeout/once

Every export of closeout/once, with its signature and doc comment: once.

once(fn) — a function that runs at most once and returns its first result thereafter (design R5).

Two packages, 262 M downloads a week between them, for this: onetime (162.3 M/wk) calls mimic-fn (99.7 M/wk) so that the wrapper it returns still answers to the wrapped function's name and length. Both are inside this layer's own incumbent tree — restore-cursor → onetime → mimic-fn — so the drop-in recipe is incomplete without it, which is the only reason a once-wrapper lives in a package about exiting.

What "preserving" means here, and why each half is load-bearing

name and length. Not cosmetics: a wrapper whose name is '' turns every stack frame and every deadline report into (anonymous), and this package's own report names handlers by fn.name. Wrapping a handler in once() must not be the reason a hang becomes unattributable.

this. A plain arrow would swallow the receiver, so obj.method = once(obj.method) would call the method against undefined — the failure arrives later, somewhere else, and looks nothing like the line that caused it. The wrapper is therefore a function expression that forwards its own this, which is the one thing an arrow cannot do.

Zero dependencies, and about as many lines as mimic-fn's README.

import { once } from 'closeout/once';

Functions

once

Wrap fn so it runs at most once.

Later calls do not run it again and do not throw: they return the first result, which is what makes this safe on an exit path where two triggers race. The arguments of a second call are ignored, deliberately and visibly — a "once" that quietly re-ran for different arguments would be a memoiser, and a memoiser on a shutdown handler is a bug with a friendly name.

function once<T extends AnyFunction>(fn: T): T;
ParameterType
fnT

Returns T

On this page