Friday, September 5, 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
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6638 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11866 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7027 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS