[javascript] Set timeout for ajax (jQuery)

$.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.

This question is related to javascript jquery html css ajax

The answer is


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".


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/


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 :)


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);
        }
    }
});?

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios