JavaScript Snippet

Run a Function Only Once

Difficulty: Easy

Wrapping a function so it runs at most once is the right tool for one-shot initialisers, lazy connection setup, and event handlers that must not double-fire. This snippet covers the canonical `once`, an async-aware version that caches the in-flight Promise, and a `resetOnce` variant for tests and feature flags. Drop it next to your event listeners and stop guarding with ad-hoc booleans.

Code Snippets
/

Run a Function Only Once

Run a Function Only Once

Wrapping a function so it runs at most once is the right tool for one-shot initialisers, lazy connection setup, and event handlers that must not double-fire. This snippet covers the canonical `once`, an async-aware version that caches the in-flight Promise, and a `resetOnce` variant for tests and feature flags. Drop it next to your event listeners and stop guarding with ad-hoc booleans.

JavaScript
Easy
3 snippets
utility
code-template
idempotency

876 views

22

The implementation is three closures: a called flag, a cached result, and the wrapper itself. After the first invocation, the wrapper returns the cached result without calling fn again, so subsequent calls are O(1) and side-effect-free. The early return result matches what callers expect: they get the same value every time, even if they forget that the work has already happened. This pairs nicely with module-level init functions, single-shot bootstrap routines, and event handlers like a click that should only ever fire once.