JavaScript How To : Deferred Code Execution with jQuery Deferreds

When building web applications I often need to execute pieces of code only after a certain condition has been met. If you use jQuery, then you are probably aware of the Deferred functionally it provides when working with Ajax calls or animations. But what if your want to use it to check some other condition – like the existence (or disappearance) of a DOM element; or a change to a JavaScript global variable? For this you would need to revert to something else – like the old setInterval – but you loose the chaining ability of the jQuery Deferred class which I love to use.

Take the following use case:

You have a modular application that loads javascript files (modules) asynchronous as it is needed. Those modules, once they are loaded and *ready*, set a variable indicating “done” – for simplicity, lets say it is window.appReady. “Ready” could mean making more asynchronous calls to the server (ie retrieve data to initialize the UI).

What I need is a utility that checks the variable periodically and once it indicates “done”, a code block is executed. The call to this utility looks like this:

    when: function(){
        return window.appReady === "ready";
.done(function(){ alert("App is ready!!"); })
.fail(function(){ alert("App is not yet ready!"); });

The above code keeps checking the window.appReady variable until its value is “ready”, at which point, it will execute the given callback function. The utility has several other input options that can be used to control how often to check the condition and for how long. See below.

I initially came across the need for this utility when I developed a widget plugin that needed to adjust (normalize) element height on that widget. The problem was that the widget could be initialized on hidden (display: none) elements making it impossible to determine the height of the elements. With that, I created this utility to check for when the widget became visible. This utility leverages the jQuery Deferred class so that we can chain multiple code execution blocks and take advantage of the different states.

The code for the utility can found in this gist:


2 thoughts on “JavaScript How To : Deferred Code Execution with jQuery Deferreds

  1. Hi Paul,
    Excellent work! Just one minor note: There seems to be a typo on line 7 of your application example (closing parenthesis missing). The line should probably read: .fail(function(){ alert(“App is not yet ready :(“)});
    Again, great work!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s