Callback that Does Its Thing on the Second Call Only

A little (javascript) closure on a lovely snowy evening in Knoxville.

There might be a better way to do this, but it seems to work.

The basic issue I ran into was that I was setting off two d3 animations, and I couldn't know which one would finish first. Whichever one finished last, I wanted something else to happen.

A solution that seems to work is to have both animations call the same callback when finished, which is set via the .each("end", callback), and on the second call to the callback do the work I wanted done.

The basic idea (here) is to define a new function, which I call MakeCallCallbackOnSecondCall, like the following:

var MakeCallCallbackOnSecondCall = function(callback) {
          var numberTimesCalled = 0;          
          var handleCallback = function() {
            numberTimesCalled++;
            if (numberTimesCalled===2) {
              callback();
            }
          }          
          return handleCallback;
      };

To use this, you give it the function you want called on the second call. For example

 var sayHelloSecondTime = MakeCallCallbackOnSecondCall(function(){alert("Hello!");});
 sayHelloSecondTime(); //nothing happens
 sayHelloSecondTime(); //alerts "Hello!"

Simple, and maybe not the most elegant solution, but the use of the javascript closure this way is something I grok a little better this year than last.

Note: there was a more general (and maybe more elegant) way to do this for the nth call I saw on stackoverflow, but I can't find it at the moment.

Popular Posts