Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

Recipe: Setting Request Timeouts

In a responsive interface, it is sometimes better to quickly say that you cannot answer in time than it is to wait for a long time. If the user is waiting for the results of an AJAX request, it is wise to add a timeout.

Listing 5.8 tries to fetch the result of the sleep function in one second. A quick glance at the first recipe in this chapter teaches us that the test server will never respond before two seconds have passed. You do not have to be psychic to predict the outcome here. . . .

Listing 5.8. Failing If the Server Takes Longer Than One Second

00 <!DOCTYPE html>
01
02 <html lang="en">
03 <head>
04   <title>The timeout property</title>
05 </head>
06 <body>
07
08 <h2>Press the button to perform the request.</h2>
09
10 <button id="trigger">GET</button>
11 <br>
12 <div id="target">
13
14
15 <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
16
17 <script>
18 // please externalize this code to an external .js file
19 $(document).ready(function() {
20
21   $('#trigger').click(function() {
22
23     $.ajax({url: 'sleep',
24         timeout : 1000
25     })
26     .done(function(data, xhr) {
27       $('#target').append('Response in time after all: ' + data);
28     })
29     .fail(function(xhr, text, error) {
30       $('#target').append('Failed as expected: ' + error);
31     });
32
33   });
34
35 });
36 </script>
37 </body>
38 </html>

Once again, the fail() callback is called. And once again, it’s called with different parameters, describing that this failure was caused by a timeout.

  • + Share This
  • 🔖 Save To Your Account