Using Jquery Deferred

I am going to give a simple example which would explains the usage of Jquery deferred concept. The Jquery deferred plays a vital role in handling asynchronous actions. The $.Deferred is used internally by many Jquery API such as ajax and animations.

The $.Deferred usage flow will be as follows.

  1. Instantiate deferred object using $.Deferrred() when some action starts.
  2. When the action completed, resolve the deferred object using resolveWith/rejectWith and your parameter.
  3. Return the promise object from the function for chaining ability

Now I am going to explain using $.Deferred object with the simple animation operation.

For that we have a HTML element as follows.

<input type="button" value="Animate" />
<div id="target" style="border: solid 1px black; width: 500px; height: 70px;"></div>

And the function which will perform the animation is as follows. The below function will animate the width of the div element from 500px to 10px. I had not written the animate function in a generic way as I am going to concentrate on using deferred promise.

    function animate() {

            //Initialize Deferred object.
            var deffered = $.Deferred();   Step 1

            width = +$("#target").outerWidth();

            var inter = setInterval(function () {
                $("#target").width(width-- + "px");

                //Stops animation when width reaches 10.
                if (width == 10) {


                    //RESOLVE THE DEFERRED WITH arguments.
          Step 2 deffered.resolveWith($("#Grid"), [{ width: width }]);

            }, 10);
            //Returns promise object to chain operation.
         Step 3   return deffered.promise();

Now the animation function can be invoked as follows. And when the animation completed, the promise object will get resolved and call the corresponding callback registered using done. If fails, the callback registered with fail will be invoked.

       //Input element click handler.
        function change() {            

            animate().done(function (e) {
                console.log(e.width); //Returns 10


And I said in the Step 3 to return the promise object. But we should be careful in using this since it sometimes led to anti-pattern.


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s