Saturday, December 28, 2024
Google search engine
HomeLanguagesJavascriptFunction that can be called only once in JavaScript

Function that can be called only once in JavaScript

Here the job is to apply restrictions so that a function can not be called more than one time. The user will be able to perform the operation of the function only once. We are going to do that with the help of JavaScript. 

Approach 1:

  • Make a function.
  • Create a local variable and set its value to false. So the function can only operate if its value is false.
  • When the function is called the first time, set the variable’s value to true and perform the operation.
  • Next time, because of variable’s value is true function will not operate.

Example: This example uses the approach discussed above. 

Javascript




let fun1 = (function () {
    let done = false;
    return function () {
        if (!done) {
            done = true;
            console.log("Function Call one time");
        }
    };
})();
 
function GFG_Fun() {
    fun1();  // It is called and result
    fun1();  // It is not called.
}
 
GFG_Fun();


Output

Function Call one time

Approach 2:

  • Make a function.
  • Create a static variable and set its value to false. So the function can only operate if its value is false.
  • When the function is called the first time, set the variable’s value to true and perform the operation.
  • Next time, because of variable’s value is true function will not operate.

Example: This example uses the approach discussed above(static variable). 

Javascript




let done = false;
 
let fun1 = (function () {
    return function () {
        if (!done) {
            done = true;
            console.log("Function Called one time");
        }
    };
})();
 
 
function GFG_Fun() {
    fun1();  // It is called and result
    fun1();  // It is not called.
}
 
GFG_Fun();


Output

Function Called one time

RELATED ARTICLES

Most Popular

Recent Comments