jake12345
jake12345

Reputation: 3

Prevent same javascript function being called multiple times

I have a javascript function initStandardProviders() which is being rendered when I load the application and the same function is loaded from diffrent modules as well. Is there an option to prevent this function from being loaded multiple time inside the same function?

function initStandardProviders(){
//A random function which should be loaded only once.
}

Upvotes: 0

Views: 2723

Answers (2)

HugeBelieve
HugeBelieve

Reputation: 322

We can use closure for these purposes

 var makeFunctionCalledOnce = function(fn){
    let called = false;
    return function(...args){
        if(!called){
            called = true;
            fn.call(this,...args);
        }
    }
  }

Now you can transpose any function to a "once called function"

function initStandardProviders(){
//A random function which should be loaded only once.
}

let newInitStandardProviders = makeFunctionCalledOnce(initStandardProviders);

// now just call newInitStandardProviders on runtime instead of initStandardProviders

Upvotes: 4

CertainPerformance
CertainPerformance

Reputation: 370679

You can set a flag in an IIFE, and toggle it on when run. If the flag is already on, don't do anything:

const initStandardProviders = (() => {
  let haveRun = false;
  return () => {
    if (haveRun) {
      return;
    }
    haveRun = true;
    //A random function which should be loaded only once.
  };
})();

const initStandardProviders = (() => {
  let haveRun = false;
  return () => {
    if (haveRun) {
      return;
    }
    haveRun = true;
    //A random function which should be loaded only once.
    console.log('running main function body');
  };
})();

initStandardProviders();
initStandardProviders();
initStandardProviders();

Upvotes: 0

Related Questions