Skip to main content
Ben Nadel at Scotch On The Rocks (SOTR) 2011 (Edinburgh) with: Darren Walker
Ben Nadel at Scotch On The Rocks (SOTR) 2011 (Edinburgh) with: Darren Walker

Catching Timeout Errors With jQuery Powered AJAX

By
Published in Comments (17)

Last week, I had to create a page that would monitoring another server for up-time (during an intensive data transfer process that was crashing out the server from time to time and would need to be re-started). When coding this page, I used the jQuery AJAX Timeout setting for the first time. It was a nice little feature. I am not sure how long an AJAX request would wait before timing out if you exclude the Timeout setting; I wonder if it would ever timeout if the request simply kept hanging?

Anyway, I thought I would just throw together a quick demo so you can see part of what I was doing. First, I am going to set up a simple ColdFusion page that allows the page to be executed with an arbitrary sleep duration:

<!--- Param the number of milliseconds to pause. --->
<cfparam name="URL.timeout" type="numeric" default="1000" />

<!--- Pause the thread. --->
<cfthread
	action="sleep"
	duration="#URL.timeout#"
	/>

<!--- Return JSON success. --->
<cfcontent
	type="text/plain"
	variable="#ToBinary( ToBase64( SerializeJSON( true ) ) )#"
	/>

As you can see, this page simply sleeps the current thread and then returns a JSON response.

Now, I set up a simple page that makes an AJAX request to the above ColdFusion page making sure to get the target page to sleep longer than the AJAX timeout setting (so as to force a timeout error):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<title>jQuery AJAX And Timeout Demo</title>

	<!-- Linked files. -->
	<script type="text/javascript" src="jquery-1.3.1.pack.js"></script>
	<script type="text/javascript">

		$(
			function(){
				// Fire off AJAX request.
				$.ajax(
					{
						// Define AJAX properties.
						method: "get",
						url: "timeout.cfm?timeout=5000",
						dataType: "json",
						timeout: (2 * 1000),


						// Define the succss method.
						success: function(){
							$( "#response" ).text( "Success!" );
						},


						// Define the error method.
						error: function( objAJAXRequest, strError ){
							$( "#response" ).text(
								"Error! Type: " +
								strError
								);
						}
					}
					);
			}
			);

	</script>
</head>
<body>

	<h1>
		jQuery AJAX And Timeout Demo
	</h1>

	<p>
		Loading AJAX.....
	</p>

	<p id="response">
		<!-- Reponse. -->
	</p>

</body>
</html>

As you can see in the AJAX properties, we are getting our target page to sleep for 5,000 milliseconds but we are only allowing a 2,000 millisecond timeout for the AJAX request. When we run this page, the following content is loaded into the DOM:

Error! Type: timeout

Based on the resultant DOM content, we can see that the Timeout setting caused the AJAX request to end in error with the error handler being invoked. Just a small demo, but I think this is a setting that I want to start working into all of my jQuery AJAX applications.

Want to use code from this post? Check out the license.

Reader Comments

1 Comments

I think we can just provide a "Cancel" link, which the user can click and cancel the request if it's taking too long.

15,902 Comments

@Chandra,

We can definitely take advantage of the abort() function on the XMLHttpRequest object; but, I think there its a good idea to build in a timeout as an AJAX event is supposed to be snappy and if its not, something is probably going wrong (or at least the user should be alerted in some way).

1 Comments

Thanks! This helped a lot.

I think that the other helper methods like getJSON, get, post, etc. should also have provision for handling timeout and other errors. I had to replace all ajax calls to use $.ajax instead.

15,902 Comments

@Hemanshu,

The methods like getJSON() are all wrappers to the .ajax() method. Underneath, they all use .ajax(); so, I guess the feeling is, they provide these short hands with less inputs so you don't have to provide them all. But, I agree - they probably should have error callbacks.

1 Comments

@ Hemanshu

You can actually use the ajaxSetup function to give all of your queries a certain timeout value as well as other options included in the $.ajax function.

You simply use
$.ajaxSetup({ timeout: 20000
});

If you want to make it specific to each request then yes, you would have to convert all of your ajax requests to use the $.ajax function.

Hope this helps someone have a bit of time :)

10 Comments

not wanting to rewrite to jQuery a complicated page already working well using Spry - Is there a Spry equivalent to
$.ajaxSetup({ timeout: 20000
});

15,902 Comments

@Mike,

Hmm, I've never really touched Spry. I've seen it, but don't know much about the specs. Try asking Ray Camden - he's Mr. Spry :)

1 Comments

I got a small problem with timeout and unreachable URLs. jQuery 1.4.2 will call the error function twice when it cannot reach the destination url.

First with status == "parsererror" and the second time with "timeout". The first results from not being able to parse the response (because there is no response).

Any ideas how to prevent that?

15,902 Comments

@Philk,

Hmm, that's an odd one. I almost think I remember seeing this discussed somewhere. I think someone may have even said that this was the expected behavior?? But, don't quote me on that - I could be way wrong.

I don't have any good suggestions other than checking for the error type and simply exiting the method if the error is not one you want deal with.

Sorry I don't have any better advice.

1 Comments

I wonder if there is a way to attach , if you will, the abort method to just one ajax function. For example , what if you have two async ajax requests? #1 keeps running, but number #2 is called, if either has error, I want to cancel and return , but it seems a bit tricky to get the function in error(ajax call #1) to return on error or cancel if the other one is still running. Did that make sense?
Thanks,
Eric Nickus
retsman

15,902 Comments

@Eric,

I'm sorry, I'm not sure that I follow exactly what you are saying. Are both AJAX requests firing off at the same time? Or does the second one fire if the first one fails?

1 Comments

Hey Ben,

I use your site pretty often so it's nice to finally put a word in ;). Maybe in jQuery 1.3.1 there was a method parameter for the $.ajax request I don't know, but in the latest 1.4.3 your method parameter is instead called type. http://api.jquery.com/jQuery.ajax/

Here's a quick sample from that page.

$.ajax({
	type: "GET",
	url: "test.js",
	dataType: "script"
});

Not trying to be a nuisance, just pointing it out =).

Anyways, you're awesome man, keep it up!

-Kevin

1 Comments

I am having a problem with the timeout function.

I have a setInterval wich does an ajax call. If the ajax call timesout, all other ajax requests will automatically timeout too..

Any idea how to solve this problem??

sample:

setInterval(function(){
ajaxCall();
}, 10000);

$.ajaxSetup({
timeout: 1000,
url : '/ajax/url.php',
type : 'post',
dataType: 'JSON',
cache: false
});

function ajaxCall() {
$.ajax({
success : function(r){
console.log(r);
},
error : function(){
}
});
}

2 Comments

jQuery's timeout is useful specially in JSONP requests (made via the same $.ajax, but with data: 'jsonp' parameter). Thanks for this post.

1 Comments

Hello, thanks a lot for this. This gave me an idea on a prototype I am working on. Also, thanks to the commentors.

$.ajaxSetup worked for me. Most of my requests are using the shorthand get, it would take much time and energy to replace 'em all.

Thanks!

1 Comments

Hi Ben,

I need help with $.ajax call. currently page is taking around 45secs for URL to respond and timeout value is set as 30*1000 .
Now to avoid timeout error I increased timeout value from 30*1000 to 50*1000 , but page still timesout in 30secs.... Could you help what I am missing (using jQuery 1.4)
Thanks in advance

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel