Create once callable functions

Another use of Javascript closures. You can create functions which are callable only once.

function createChance() {
  var chanceLeft = true;
  return function() {
    if (chanceLeft) {
      console.log("This was the only chance you had.");
      chanceLeft = false;
    } else {
      console.log('Sorry: you already used your chance');

var chance = createChance();
// This was the only chance you had.
// Sorry: you already used your chance

These kind of functions can be useful when you need to implement security pattern in Javascript. Once created function should be used only once. To call it again you need to request its creation again. Another version of this kind of patters can be to implement envelops, where an envelop can be opened only by the person who has the key to open it.

3 thoughts on “Create once callable functions

  1. Hey,

    Interesting use of the Singleton Pattern in JS. I believe you meant that the function can be created once and called multiple times, since you are calling it twice here. In order to reset the function to its original state, you would have to recreate it, which is the basic essence of a singleton function/class.

    On the server side, how would this handle multiple requests or race conditions? I know that Java and C# do that via locking/synchronization. Is there a similar way for JS?

  2. Hey just wanted to give you a quick heads up and let you know a few of the images aren’t loading correctly. I’m not sure why but I think its a linking issue. I’ve tried it in two different internet browsers and both show the same outcome.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>