219
$.ajax({
    url: "test.html",
    error: function(){
        //do something
    },
    success: function(){
        //do something
    }
});

Sometimes success function works good, sometimes not.

How do I set timeout for this ajax request? In example, 3 seconds, if time is out, then show an error.

The problem is, ajax request freezes the block until finishes. If server is down for a little time, it will never end.

Brandon Boone
  • 16,281
  • 4
  • 73
  • 100
James
  • 42,081
  • 53
  • 136
  • 161
  • 2
    You need a `,` there after the `}`. – pimvdb Mar 07 '11 at 21:44
  • 2
    take look at this > http://stackoverflow.com/questions/12930759/how-to-call-a-jquery-function-onload-with-some-delay/12930892#12930892 – Bahram Oct 18 '12 at 07:30
  • 1
    possible duplicate of [jQuery $.ajax timeout setting](http://stackoverflow.com/questions/3543683/jquery-ajax-timeout-setting) – nathanchere Feb 05 '14 at 07:35

6 Answers6

381

Please read the $.ajax documentation, this is a covered topic.

$.ajax({
    url: "test.html",
    error: function(){
        // will fire when timeout is reached
    },
    success: function(){
        //do something
    },
    timeout: 3000 // sets timeout to 3 seconds
});

You can get see what type of error was thrown by accessing the textStatus parameter of the error: function(jqXHR, textStatus, errorThrown) option. The options are "timeout", "error", "abort", and "parsererror".

Intelekshual
  • 7,444
  • 1
  • 21
  • 28
  • 4
    regarding catching timeout error http://stackoverflow.com/questions/3543683/determine-if-ajax-error-is-a-timeout – Adriano Jul 02 '14 at 07:30
  • 1
    Just doesn't seem to work for me, timeout: 1, confirmed it's being passed, just never times out – PandaWood May 13 '16 at 06:56
  • Make sure to wrap the entire $.ajax call with a try/catch. Aborts are not caught by jQuery and will be thrown outside of the $.ajax call. – justdan23 Dec 13 '19 at 15:08
125

Here's some examples that demonstrate setting and detecting timeouts in jQuery's old and new paradigmes.

Live Demo

Promise with jQuery 1.8+

Promise.resolve(
  $.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
  })
).then(function(){
  //do something
}).catch(function(e) {
  if(e.statusText == 'timeout')
  {     
    alert('Native Promise: Failed from timeout'); 
    //do something. Try again perhaps?
  }
});

jQuery 1.8+

$.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
}).done(function(){
    //do something
}).fail(function(jqXHR, textStatus){
    if(textStatus === 'timeout')
    {     
        alert('Failed from timeout'); 
        //do something. Try again perhaps?
    }
});​

jQuery <= 1.7.2

$.ajax({
    url: '/getData',
    error: function(jqXHR, textStatus){
        if(textStatus === 'timeout')
        {     
             alert('Failed from timeout');         
            //do something. Try again perhaps?
        }
    },
    success: function(){
        //do something
    },
    timeout:3000 //3 second timeout
});

Notice that the textStatus param (or jqXHR.statusText) will let you know what the error was. This may be useful if you want to know that the failure was caused by a timeout.

error(jqXHR, textStatus, errorThrown)

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests.

src: http://api.jquery.com/jQuery.ajax/

Brandon Boone
  • 16,281
  • 4
  • 73
  • 100
27

You could use the timeout setting in the ajax options like this:

$.ajax({
    url: "test.html",
    timeout: 3000,
    error: function(){
        //do something
    },
    success: function(){
        //do something
    }
});

Read all about the ajax options here: http://api.jquery.com/jQuery.ajax/

Remember that when a timeout occurs, the error handler is triggered and not the success handler :)

Martin Jespersen
  • 25,743
  • 8
  • 56
  • 68
2

use the full-featured .ajax jQuery function. compare with https://stackoverflow.com/a/3543713/1689451 for an example.

without testing, just merging your code with the referenced SO question:

target = $(this).attr('data-target');

$.ajax({
    url: $(this).attr('href'),
    type: "GET",
    timeout: 2000,
    success: function(response) { $(target).modal({
        show: true
    }); },
    error: function(x, t, m) {
        if(t==="timeout") {
            alert("got timeout");
        } else {
            alert(t);
        }
    }
});​
Community
  • 1
  • 1
Rudolf Mühlbauer
  • 2,511
  • 16
  • 18
  • H-Bahrami and Rudolf Mühlbauer thanks for reply but i am new in ajax so please clarify through my code...because i have already see these answer but i don't know What's going on..so please help me... –  Oct 18 '12 at 07:44
  • how I can do through .load() ? It is possible or not ? –  Oct 18 '12 at 10:02
  • @S.S, try looking for timeout in the documentation of load: http://api.jquery.com/load/ -- and i had a typo in my code, corrected. – Rudolf Mühlbauer Oct 18 '12 at 17:18
1

Don't forget to check NginX settings also if your requests are going through NginX.

Ajax options.timeout is one thing but nginx request timeout might need adjusting also.

See https://ubiq.co/tech-blog/increase-request-timeout-nginx/

Riaan Schutte
  • 535
  • 1
  • 5
  • 14
1

your request should be like below.

client.ajax({
               url:'web-url',
               method: 'GET',
               headers: 'header',
               timeout: 3000
          });
Lovekush Vishwakarma
  • 3,035
  • 23
  • 25