This page looks best with JavaScript enabled

Allow a function call once and only once

 ·   ·  ☕ 1 min read

Allow a function to be called once and only once.

We have previously seen an example where debounce can be used to call a function once and can ignore subsequent calls.

There is a shorthand way to allow a single function call that if you are not interested in the debounce part of the problem.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
function getSum(x, y) {
  arguments.callee.count = arguments.callee.count || 0;
  arguments.callee.count++;

  console.log(arguments.callee.count);
  // 1 2 3
  if (arguments.callee.count <= 1) {
    console.log("sum", x + y);
    return x + y;
  }
}

getSum(4, 2); // 6
getSum(1, 2); // no sum
getSum(0, 1); // no sum

This is cool, right? Ok then, here’s what you do for homework - discover a way to allow calling any given function twice and only twice.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things