This page looks best with JavaScript enabled

Executing Functions Only Once in Javascript

 ·   ·  ☕ 1 min read

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
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).

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things