To handle AJAX timeouts and retries in jQuery, you can make use of the timeout
and error
options provided by the $.ajax()
method. Here's an example:
var maxRetries = 3;
var retryCount = 0;
function makeAjaxRequest() {
$.ajax({
url: 'your-url',
type: 'GET',
timeout: 5000, // Set a timeout value in milliseconds
success: function(response) {
// handle the successful response
},
error: function(jqXHR, textStatus, errorThrown) {
if (textStatus === 'timeout' && retryCount < maxRetries) {
// Retry the AJAX request
retryCount++;
makeAjaxRequest();
} else {
// handle the error
}
}
});
}
In the above example, timeout
option is set to 5000 milliseconds (5 seconds). If the AJAX request fails to receive a response within this timeout value, the error callback is triggered with the textStatus parameter set to "timeout".
Inside the error callback, we check if the textStatus
is "timeout" and if we haven't exceeded the maxRetries
count. If both conditions are met, we increment the retryCount
and make the AJAX request again by calling the makeAjaxRequest()
function recursively.
Note that you may adjust the timeout value (5000
) and the maximum number of retries (3
) based on your specific requirements.