Function in JavaScript that can be called only once
snippet in javascript

Function in JavaScript that can be called only once

user4030

// this function does nothing
function noop() {};

function foo() {
    foo = noop; // swap the functions

    // do your thing
}

function bar() {
    bar = noop; // swap the functions

    // do your thing
}

Function in JavaScript that can be called only once

user1178

  // Returns a function that will be executed at most one time, no matter how
  // often you call it. Useful for lazy initialization.
  _.once = function(func) {
    var ran = false, memo;
    return function() {
      if (ran) return memo;
      ran = true;
      memo = func.apply(this, arguments);
      func = null;
      return memo;
    };
  };

Function in JavaScript that can be called only once

user7941

var something = (function() {
    var executed = false;
    return function() {
        if (!executed) {
            executed = true;
            // do something
        }
    };
})();

something(); // "do something" happens
something(); // nothing happens

Function in JavaScript that can be called only once

user9952

var quit = false;

function something() {
    if(quit) {
       return;
    } 
    quit = true;
    ... other code....
}