David Board David Board - 28 days ago 7
Ajax Question

Jquery AJAX timeout not functioning as expected

I am trying to write a simple Jquery AJAX poll. I want to make sure that requests don't 'back up' in the browser if the web-server is being slow (which in my specific situation is very frequently...).

Here's my code:

(function poll() {
$.ajax({
url: CONFIG.apiBase,
type: 'GET',
data: { name: DESTINATIONS },
traditional: true,
success: updateDisplay,
error: getError,
complete: setTimeout(poll, 2000),
timeout: 10000,
});
})();


The way I think this should work is that if the request is successful, it will do
updateDisplay
and then wait 2 seconds before starting another poll request.

However, if my server is being super slow and can't respond within 10 seconds then
getError
will be called, the request will be cancelled and finally it will wait for 2 seconds before trying to poll again.

However, what actually happens is that the browser consistently polls the server every 2 seconds, causing the requests to back up if the server is being slow:

enter image description here

Am I fundamentally misunderstanding how
timeout
is supposed to work?

Answer

The problem is your setTimeout(poll, 2000) line. At the moment it's calling your poll() function every 2 seconds as you don't wait for the previous request to finish. To fix this, wrap it in an anonymous function:

(function poll() {
    $.ajax({
        url: CONFIG.apiBase,
        type: 'GET',
        data: { name: DESTINATIONS },
        traditional: true,
        success: updateDisplay,
        error: getError,
        complete: function() {
            setTimeout(poll, 2000)
        },
        timeout: 10000,
    });
})();
Comments