Execute a function once

Run a function on the first call and return that result afterwards.

JavaScriptNode.js & browsers Version 1.0.0 · MIT · .md

execute-a-function-once.js
function once(fn) {
  let done = false, result;
  return (...args) => {
    if (!done) { result = fn(...args); done = true; }
    return result;
  };
}

Usage

usage.js
let connections = 0;
const connect = once(() => ({ id: ++connections }));
connect(); // → { id: 1 }
connect(); // → { id: 1 }
connections; // → 1

Lines marked → were executed in Node.js 22 and in headless Chromium, and each result was compared with the value shown. Lines marked e.g. are illustrative.

Know the limits

  • Typical use: create one API client or connection pool lazily, on first use.
  • If fn throws, done stays false and the next call tries again. A rejected promise, however, is a result and is kept.
  • The original forwarded no arguments and overwrote fn with its result.

The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.

Source & maintenance

Based on Execute a function once from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

Forwards arguments and keeps the result separate from the function; a throwing first call can be retried. Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.

Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.

Usage lines executed in Node.js 22 and headless Chromium; no external services · reviewed October 28, 2026.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.