Dev HelpersOpen library
← Back

Run a function once

Run a function once. A self-contained example using the JavaScript runtime.

Open this example in the interactive library

Source code

const once = (f) => {
  let called = false,
    result;
  return (...args) => {
    if (!called) {
      result = f(...args);
      called = true;
    }
    return result;
  };
};
const next = once(() => 42);
console.log(next(), next());

Sample output

42 42