Search code examples
javascriptjqueryajax

How to correctly handle ajax timeouts


For example, a user want to login, the connection is slow or the request is stuck into some network , then the user waits, but sometimes is better resend the request than waiting.

Questions:

  • What would be the desirable waiting time? (no uploading files, just simple login) I've put 15 secs, but maybe it's too much.
  • What's the best solution?

1) Keep the user waiting till he decides to click login again

2) Set an ajax timeout

$.ajax({

url: '{{ url('/login') }}',
data: data,
method: 'POST',
timeout: 15000, 

and display them an error

error: function(data, status, error){

if(status==="timeout") {
var errorString = 'Please retry. Ref Timeout';                      
}

3) do an auto retry (code)

$.ajax({
url : 'someurl',
type : 'POST',
data :  ....,   
tryCount : 0,
retryLimit : 3,
...
error: function(data, status, error){
    if (status == 'timeout') {
       this.tryCount++;
       if (this.tryCount <= this.retryLimit) {
       //try again
           $.ajax(this);
           return;
       }            
       return;
    }

4) Use a wrapper function over the ajax

setTimeout(function(){
    $.ajax({...})
}, 15000);

5) Some other options


Solution

  • You can do both, try 2 times and then fail:

    $.ajax({
        url: '{{ url('/login') }}',
        data: data,
        method: 'POST',
        timeout: 5000, // Set timeout to 5000ms (5 seconds)
        retryCount: 0, // Number of retries, starts at 0
        retryLimit: 1, // The maximum number of retries
        success: function(data) {
            // do stuff
        },
        error: function(data, status, error) {
            if (status === "timeout") {
                this.retryCount++;
                if (this.retryCount <= this.retryLimit) {
                    console.log("Retrying");
                    $.ajax(this);
                } else {
                    alert('Timeout');                       
                }
                return;
            }
            // Handle other errors...
        }
    });