Neues Node.js-Buch
Alle Artikel

Create a function that only executes once

Problem

You want to be sure that the logic inside a function is executed only once.

Ingredients

  • a self-defining function

Directions

  1. Given: a function that is called twice, but should not do anything the second time it is called.

    function printSomething() {
      console.log('something');
    }
    printSomething();            // (1) Ok
    printSomething();            // (2) Should not be allowed
  2. Add a variable to memorize if the function has been called.

    function printSomething() {
      let called = false;
      console.log('something');
    }
  3. If it is false, then return undefined.

    function printSomething() {
      let called = false;
      if(called) {
        return undefined;
      }
      console.log('something');
    }
  4. … otherwise set the variable to true

    function printSomething() {
      let called = false;
      if(called) {
        return undefined;
      } else {
        called = true;
      }
    }
  5. … execute the remaining logic of the function …

    function printSomething() {
      let called = false;
      if(called) {
        return undefined;
      } else {
        called = true;
        console.log('something');
      }
    }
  6. … and overwrite the function to do nothing.

    function printSomething() {
      let called = false;
      if(called) {
        return undefined;
      } else {
        called = true;
        console.log('something');
        printSomething = function() {};
      }
    }
  7. Voilá, now if printSomething() is called a second time, it simply does nothing.

    printSomething();        // (1) Ok
    printSomething();        // (2) Does nothing

    Notes

  8. A function that overwrite itself is also called a self-defining function.

Alternative recipes

  • In tomorrow’s recipe we will see how to further improve the shown recipe.