Function in javascript that can be called only once

Function in javascript that can be called only once

I need to create a function which can be executed only once, in each time after the first it won’t be executed. I know from C++ and Java about static variables that can do the work but I would like to know if there is a more elegant way to do this?


Solution 1:

If by “won’t be executed” you mean “will do nothing when called more than once”, you can create a closure:

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

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

In answer to a comment by @Vladloffe (now deleted): With a global variable, other code could reset the value of the “executed” flag (whatever name you pick for it). With a closure, other code has no way to do that, either accidentally or deliberately.

As other answers here point out, several libraries (such as Underscore and Ramda) have a little utility function (typically named once()[*]) that accepts a function as an argument and returns another function that calls the supplied function exactly once, regardless of how many times the returned function is called. The returned function also caches the value first returned by the supplied function and returns that on subsequent calls.

However, if you aren’t using such a third-party library, but still want such a utility function (rather than the nonce solution I offered above), it’s easy enough to implement. The nicest version I’ve seen is this one posted by David Walsh:

function once(fn, context) { 
    var result;
    return function() { 
        if (fn) {
            result = fn.apply(context || this, arguments);
            fn = null;
        return result;

I would be inclined to change fn = null; to fn = context = null;. There’s no reason for the closure to maintain a reference to context once fn has been called.

[*] Be aware, though, that other libraries, such as this Drupal extension to jQuery, may have a function named once() that does something quite different.

Solution 2:

Replace it with a reusable NOOP (no operation) function.

// 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

Solution 3:

UnderscoreJs has a function that does that,

  // 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;

Solution 4:

Point to an empty function once it has been called:

function myFunc(){
     myFunc = function(){}; // kill it as soon as it was called
     console.log('call once and never again!'); // your stuff here
<button onClick=myFunc()>Call myFunc()</button>

Solution 5:

Talking about static variables, this is a little bit like closure variant:

var once = function() {
    if(once.done) return;
    console.log('Doing this once!');
    once.done = true;

once(); once(); 

You could then reset a function if you wish:

once.done = false;

Solution 6:

var quit = false;

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