Set timeout for ajax (jQuery)

James picture James · Mar 7, 2011 · Viewed 425.7k times · Source
$.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.

Answer

Intelekshual picture Intelekshual · Mar 7, 2011

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