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

Chapter 3. Deferred Recipes

In this chapter you will find many examples of using jQuery deferreds. These are all based on actual use cases. The intention is to show you a broad collection of real-world uses of deferreds in order to make this book maximally useful.

Although we’ve arranged the examples to be read in order of increasing difficulty, most of them can be read in isolation. We encourage you to “dip in” wherever it’s useful.

A Replacement for the setTimeout Function

Sometimes, when using a site such as Twitter or Gmail, a warning message appears when an asynchronous task is taking too long. For example, Twitter will replace the “spinner” at the bottom of their infinite scroll with an “oops” message along with a suggestion that you click a link to trigger the request again or refresh the page. Gmail is cleverer: when there is a connectivity problem, it displays a warning message and then counts down until the point at which it retries the network call that failed.

There is a built-in function in JavaScript called setTimeout. It works like this:

setTimeout(function(){
    console.log('Display after half a second');
}, 500);
console.log('Display immediately (unblocked)');

The result of this is:

Display immediately (unblocked)
Display after half a second

Implementing the functionality described above using just setTimeout might be hard to do in a clear and comprehensible way, especially if there were the potential for nested calls to setTimeout.

This kind of thing is easy to achieve with ...

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