Well, messing around with asynchronous function callbacks can become messy :). setInterval() is one of them, therefore .ajax() .
You should try using setTimeout() and just run the next .ajax() call when the last one has completed.
(function repeat(){ $.ajax({ async: true, url: 'gohere', dataType: 'text', cache: false, timeout: 5000, success: function(result, textStatus, XMLHttpRequest) { alert('textStatus: ' + textStatus + ",\nXHR.readyState: " + XMLHttpRequest.readyState + ",\nXHT.status: " + XMLHttpRequest.status); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert('textStatus: ' + textStatus + ",\nXHR.readyState: " + XMLHttpRequest.readyState + ",\nXHT.status: " + XMLHttpRequest.status); }, complete: function(XMLHttpRequest){ setTimeout(repeat, 3000); } }); }());
If you insist that .ajax() be as close as possible to 3 seconds, you can interrupt your last (possibly launched) ajax request before starting a new one.
Therefore, assign the .ajax() return variable as
var currentxhr = $.ajax({});
and add the beforeSend to your .ajax() call. Within this call handler
currentxhr.abort();
This will result in the cancellation of a possibly running request.
jAndy source share