title: Asynchronously delay JS until a condition is met
body: <p>I have a class, <code>ChatRoom</code>, that can only render after it receives a long-running HTTP request (it could take 1 second or 30 seconds). So I need to delay rendering until <code>ChatRoom.json</code> is not null.</p>
  
  <p>In the code below, I'm using Closure Library's <a href="http://code.google.com/p/closure-library/source/browse/trunk/closure/goog/async/conditionaldelay.js"><code>goog.async.ConditionalDelay</code></a>. It works, but is there a better way (maybe without needing Closure Library) to do this?</p>
  
  <pre><code>ChatRoom.prototype.json = null; // received after a long-running HTTP request.
  
  ChatRoom.prototype.render = function() {
      var thisChatRoom = this;
  
      function onReady() {
          console.log("Received JSON", thisChatRoom.json);
          // Do rendering...
      }
  
      function onFailure() {
          alert('Sorry, an error occurred. The chat room couldn\'t open');
      }
  
      function isReady() {
          if (thisChatRoom.json != null) {
              return true;
          }
          console.log("Waiting for chat room JSON...");
          return false;
      }
  
      // If there is a JSON request in progress, wait until it completes.
      if (isReady()) {
          onReady();
      } else {
          var delay = new goog.async.ConditionalDelay(isReady);
          delay.onSuccess = onReady;
          delay.onFailure = onFailure;
          delay.start(500, 5000);
      }
  }
  </code></pre>
  
  <p>Note that "while (json == null) { }" isn't possible because that would be synchronous (blocking all other JS execution).</p>