0

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.
}
1
  • 2
    Take a look at singleton pattern. Commented Sep 30, 2019 at 3:03

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

If this solves your query please make sure to accept the answer
0

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();

1 Comment

When an answer solves your problem, you may consider upvoting and/or marking it as Accepted (check the checkbox on the left) to indicate that the issue is resolved :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.