Skip to content

getJSON timeout handling

An answer to this question on Stack Overflow.

Question

I am using jQuery getJSON() function. This function getting data with no problem. But sometimes waiting, waiting waiting... And my loading bar showing loading loading loadin at center of page. So jQuery ajax() function have an timeout variable. But i want to use getJSON function. And i think that i can use ajaxStart() and ajaxStop() functions. But how?

$('.loadingDiv')
	.hide()
	.ajaxStart(function() {
		$(this).fadeIn();
		setTimeout("throw '';",15000) //i used this but didn't work
		setTimeout("return;",15000) //i used this but didn't work
		setTimeout("abort();",15000) //i used this but didn't work.(Abort all ajax events)
	})
	.ajaxStop(function() {
		$(this).fadeOut();
	});

Answer

There's always the nuclear route as well:

//Set AJAX timeout to 10 seconds
$.ajaxSetup({
  timeout: 10*1000
});

This will set all the AJAX requests your program makes (even via $.getJSON) to have a time out of 10 seconds (or what have you).