- Recipe: Setting Up an Example Server in Node.js
- Recipe: Performing a GET Request
- Recipe: Loading HTML Directly
- Recipe: Handling the Result by Using Promises
- Recipe: Handling Server Errors
- Recipe: Catching Page-not-Found Results
- Recipe: Handling Page Redirects
- Recipe: Setting Request Timeouts
- Recipe: Passing HTTP Headers
- Example: Validating Form Input on the Server Side
- Recipe: Loading XML
- Recipe: Listening to AJAX Events
- Recipe: Reading JSONP from an External Server
- Summary
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="https://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.