Saturday, October 18, 2025
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

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS