running a function only once in javascript

1 min read  •  21 June 2023
Views:

using 'once' npm package

  • Install once npm package
npm i once
  • Wrap your function which you want to call once
import once from "once";

function greet() {
  console.log("Inside greet -", "Hello World");
}

const greetOnce = once(greet);

greetOnce();
greetOnce();
greetOnce();
  • Output
once-npm-output

Note: Incase your function returns something, it will call the function only once and memoize the returning value to return for subsequent calls

using custom polyfill for once

  • creating our own once function
function once(fn) {
  let ran = false;
  let result;
  return function () {
    if (ran) return result;
    result = fn.apply(this, arguments);
    ran = true;
    return result;
  };
}
  • Wrap your function which you want to call once, following is the same example with output
once-polyfill-output

References