Calling Function only once

Could anyone help me with this troubleshooting?

var something = (function() {
  var executed = false;
  return function() {
    if (!executed) {
      executed = true;
      alert("Hi");
    }
  };
})(); //Removing the following calls the function does not execute with parenthesis

something(); //Happens
something(); //Nothing happens

My Approach:

var only = (function once() {
  alert("Kaixo");
  only = false;
})(); //That parenthesis calls the function

only(); //Calls the function 
only(); //Nothing happens

If my example is run before the original, breaks. Continuing of this topic: Function in javascript that can be called only once

Upvotes: 2

Views: 112

Answers (3)

Maheer Ali
Maheer Ali

Reputation: 36564

You are setting the only to the value returnted by function i.e undefined.Even if you don't call it directly it will not work because false can't be called.

You can set the function to another dummy function which have nothing.

function only(){
   alert("Kaixo");
   only = function(){}
}

only(); //Calls the function 
only();

Upvotes: 4

arkeros
arkeros

Reputation: 177

Here only is a function, not a boolean. So, instead of overriding it to false, override it to an empty function. See:

var only = (function once() {
    alert("Kaixo");
    only = function () {};
}); // Don't call the function!

only(); // Calls the function 
only(); // Nothing happens

Upvotes: 3

Agustin Eloy Barrios
Agustin Eloy Barrios

Reputation: 128

var only = (function once() {
  var executed = false; // Inits the flag;
  return function() {
    if (!executed) {      
      executed = true; //Set the flag
      alert("Kaixo");
    }
}  

})(); //That parenthesis calls the function

only(); //Calls the function 
only(); //Nothing happens

Upvotes: 0

Related Questions