Reusable Debounce Function

Let us see how to execute a specified function only once in the life time of the program.

The Simple Way

The easiest way is to use a global variable and remember the function execution. We can then ignore all future invocations.

let saidHello = false;

function sayHello() {
  console.log("hello world");
  saidHello = true;
}

function helloOnce() {
  if (!saidHello) sayHello();
}

helloOnce(); // hello world
helloOnce(); // nothing
helloOnce();

The Reusable Way

We can apply concepts similar to our debounce utility to execute a function once and only one time.

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

function sayHello() {
  console.log("hello world");
}

var helloOnce = execOnce(sayHello);

helloOnce(); // hello world
helloOnce(); // nothing but emptiness
helloOnce();
helloOnce();

We have made the function reusable for any number of functions, and achieved the same goal as option (1).

comments powered by Disqus