Friday, 26 April 2013 00:00

jQuery Progress and Promises

Written by 
Rate this item
(1 Vote)

Aside from promises and the deferred object in jQuery there is also progress. As we have seen in the other post about promises, promises only resolve (done or fail) after an action is performed. We cannot trigger the change of state in a promise we only register for its events. We have no control over its state. We cannot tell a promise to resolve. We also looked at the $.Deferred object. The $.Deferred object gave us a little bit more control over a promise and we saw that it is indeed a promise. We can control state on and trigger its done() or fail() methods and notify any registered call backs. The advantage of using promises is that it not only cleans our code but provides a nice Pub/Sub substitution for one off events with distinct outcomes. But now we come to the progress method added in jQuery 1.7 to promises. Lets take a look at some code.

 

<button id="myButton">Click Me</button>
 
    $(function (){
        var deferred = new $.Deferred();
        var time = 0;
        deferred.progress(function (data){
            console.log(data);
        });
        deferred.done(function (data){
            console.log('we have reached ' + data + ' seconds');
        });
        $('#myButton').click(function (){
            setInterval(function(){
                time +=1;
                if(time===10){
                    deferred.resolve(time);
                }  else{
                    deferred.notify(time);
                }
            },1000);
        });
    });
 

So the key here is to see that the progress is a method of the deferred and that it can help us in literally checking the progress of an async action. In our case the async action is the timer function as it nears the 10 second mark. A practical example of this might be during the execution of an animation or the playing of a movie or the progress towards some quota. The progress is just some way to keep track of the state as it approaches the desired done() value.

Read 1073 times Last modified on Friday, 26 April 2013 18:20

Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

thiswildorchid I'm on github