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

877 views

22

function once(fn) {
    let called = false;
    let result;
    return function onceCaller(...args) {
        if (called) return result;
        called = true;
        result = fn.apply(this, args);
        return result;
    };
}

const init = once(() => {
    console.log('initialising...');
    return { ready: true };
});

console.log(init()); // initialising... { ready: true }
console.log(init()); // { ready: true }   (no second log)
console.log(init()); // { ready: true }

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.