2

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

Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
  • 2
    You are resetting `only` to `false`, so it doesn't run again because `false` isn't a function. – Get Off My Lawn May 03 '19 at 15:57
  • @GetOffMyLawn only is undefined because the once function returns nothing. That's because `only` is set to `false`, *then* to the value returned by the called function, `undefined`. http://i.stack.imgur.com/ado5W.png – Maxime Launois May 03 '19 at 16:01
  • Could anyone explain me the first case? I don't understand, first, why the parenthesis does not call the function, and second why does not the second call happen? Thank you – Xabier Aparicio Muñoa May 03 '19 at 16:34

3 Answers3

4

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();
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
3

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
arkeros
  • 177
  • 3
  • 1
    Be interesting to know why this has been down-voted. Yes, it's basically the same answer as @Maheer Ali, but it was answered pretty much the same time, and he is a new contributor so it's expected that it will take longer to post an answer. – Keith May 03 '19 at 16:04
  • if the code works its answer valid, maybe no the most optime answer, but still right, always is good see all ways to do something, some people dont see that – Black Hole May 03 '19 at 16:10
0

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