O'Reilly logo

Learning jQuery Deferreds by Nicholas H. Tollervey, Terry Jones

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appendix A. Hints for Selected Challenges

Here you’ll find solutions or hints for almost all the challenges in the book. Where an answer requires a significant amount of code, we make some suggestions but have left the coding to you.

A Replacement for the setTimeout Function

  1. This is pretty easy:

    function wait(timeout){
        return $.Deferred(function(deferred){
            setTimeout(deferred.resolve, timeout);
        }).promise();
    }
  2. You’d write something like this:

    var promise = wait(500);
    
    promise.done(function(){
        console.log('Timeout fired!');
    });
    
    one(promise);
    two(promise);

    Of course the one and two functions have to be able to accept a promise.

    We described this challenge as “subtly different” because it’s meant to demonstrate that our replacement setTimeout function is more than just a syntactic nicety. It gives you something you didn’t have before: a value that you can pass around to others. Although this is a trivial example, the principle is important.

  3. We just need to store the timeout identifier and add a function to the returning promise to clear the timeout and reject the deferred:

    function wait(timeout){
        var deferred = $.Deferred(),
            promise = deferred.promise(),
            timeoutId = setTimeout(deferred.resolve, timeout);
    
        promise.cancel = function(){
            clearTimeout(timeoutId);
            deferred.reject.apply(deferred, arguments);
        };
    
        return promise;
    }

    Note that this isn’t the best coding style. We probably shouldn’t be adding attributes to the promise in this way. How would you fix this shortcoming? While you’re at it, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required