0

I am making an AJAX call every 20th second of every minute and updating some data. Now sometimes when i make a call, by the time the next call happening, it still hasn't received the data from the last call thereby stacking both the calls. This keeps happening and the server is getting choked in some cases.

What i want is to cancel the AJAX call for that minute in case the response to the previous call hasn't been received yet.

This is my code:

setInterval(function(){
let now = new Date();
if(now.getSeconds() === 20){
    $.ajax({
        url: url,
        headers: { 'x-cyclops-ajax': 'yes' },
        method: 'POST',
        dataType: 'json',
        success: function(data) {
            var chart = $('#container').highcharts();
            var keys = Object.keys(data["histData"]);
            $( "#main-div" ).empty();
            for( var i=0; i< keys.length; i++) {
                chart.series[i].setData(data["histData"][keys[i]]["histFailure"], true);
                $('#main-div').append( '<div class="homepage-availability-inner-div"><h1 class="homepage-availability-text"> ' + keys[i] + ': <span class="dashboard-success">' + data["availData"][keys[i]] + ' </span> </h1></div>');
            }
            chart.xAxis[0].setCategories(data["histKeys"]);
            console.log("Data:" + JSON.stringify(data["availData"]));
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log("Did not hit the AJAX call");
        }
    });
}
}, 1000);

Any help is appreciated.

Nikhil Tikoo
  • 365
  • 1
  • 9
  • 31
  • 2
    You can set a timeout as explained in the [doco](http://api.jquery.com/jquery.ajax/). Or call `.abort()` on the object returned by `$.ajax()`. – nnnnnn Feb 21 '17 at 05:24
  • 1
    As @nnnnnn says: `$.ajax({....., timeout: 20000, ...});`. – Amadan Feb 21 '17 at 05:25
  • @Amadan Will setting the timeout stop the processing of data on the server side too? – Nikhil Tikoo Feb 21 '17 at 05:43
  • That depends on your server. For example, AFAIK, Apache is supposed to terminate CGI scripts when connection closes, but other protocols have no way to do that automatically. – Amadan Feb 21 '17 at 05:51
  • @Amadan Thanks both of you. This is what i was looking for. :) – Nikhil Tikoo Feb 21 '17 at 05:59

0 Answers0