The title is intimidating, but fear not. This will be short, sweet and probably really easy to understand. And you’ll have something to impress me with in interviews if you ever have the pleasure.

Why?

A while back I was writing some code and it turned out it was executed by two different code paths. In one case, the control was all ready and the code needed to be executed right away. In the other case, the control wasn’t ready but would be shortly after the window.load event has been fired. Yea I’m not explaining it very well, but really it doesn’t matter, lets see code.

Code

  1. var isLoaded = false;
  2.     (function() {
  3.         if(isLoaded) {
  4.             document.getElementById("out").innerHTML = "Loaded";
  5.             return;
  6.         }
  7.        
  8.         // Every 10th of a second call this method again.
  9.         document.getElementById("out").innerHTML += "Trying Again<br/>";
  10.         setTimeout(arguments.callee, 100);
  11.        
  12.         // If your inside an object, you probably want to keep the THIS pointer.
  13.         // For that, you would do the following.
  14.         // var self = this, fn = arguments.callee;
  15.         // setTimeout(function() { fn.call(self); }, 100);
  16.        
  17.         // The page will be loaded in 3 seconds
  18.         // We would probably want to wait for something like
  19.         // a DOM event, but its just sample code. So...
  20.         setTimeout(function() { isLoaded = true; }, 3000);
  21.     })();

We have both techniques of the example in use here, a self executing anonymous function, and a recursive function.

For the self executing anonymous function, we are wrapping our function in parenthesis and then calling it just like any other function.

  1. // The anonymous part
  2. (function(){})();

For the self executing part, we get a reference to the function using arguments.callee, which just so happens to be itself. With it we can use a setTimeout to have the function try again later. We could have just kept calling it, but with javascripts single threaded nature, I would think nothing would happen while your calling your function over and over.

  1. (function(){
  2. // BAD
  3. // At least in our case. You could have
  4. // a perfectly justifiable reason for doing this
  5. // though.
  6. arguments.callee();
  7. })();

You can see a live example of this code here

No comments

Leave a Reply