Chapter 15.1.9. Ajax, Timers, and Cancellation Combined

What if you want to apply a timeout to an Ajax call to gracefully handle the case where the user loses Internet connectivity or your server becomes otherwise unavailable? It becomes trivial if you combine the tools we’ve discussed in these last few segments:

d = loadJSONDoc("your_url");
callLater(30, d.cancel);

This adds a silent timeout. If you want an alert error message, you can just use JavaScript’s closures to create a function that does the right thing:

d = loadJSONDoc("your_url");
callLater(30, function() {
    if (d.fired == -1) {
        alert("Unable to talk to the server!");
        d.cancel();
    }
});

This example checks the value of the fired attribute of the Deferred. fired starts at -1, which ...

Get Rapid Web Applications with TurboGears: Using Python to Create Ajax-Powered Sites now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.