WatsMyName
WatsMyName

Reputation: 4478

jQuery aborting ajax calls not working properly

I am trying to abort all pending ajax calls if I click a button. I have the following javascript codes.

var MyApp = function() {
    this.xhrPool = [];
}

MyApp.constructor = MyApp;

MyApp.prototype.fetchDataFromApi = function() {
    var rows = $("tr.data-row");

    var _obj = this;

    rows.each(function(index, rowData){
        $.ajax({
            type: "GET",
            url: "http://wwww.example.com/somepage/",
            dataType: "json",
            beforeSend: function(jqXHR){
                _obj.xhrPool.push(jqXHR);
            },
            success: function(response){
                //do something here on successful call
            },
            complete: function(jqXHR){
                var i = _obj.xhrPool.indexOf(jqXHR);
                if(i > -1) _obj.xhrPool.splice(i,1);
            },
            error: function(request, status, error){
                //do something else here on ajax error
            }
        });

    });
}

MyApp.prototype.AbortAllAjaxCall = function(){
    if(this.xhrPool.length > 0){
        var xhrPoolLength = this.xhrPool.length;

        for(x in this.xhrPool){
            this.xhrPool[x].abort();
            this.xhrPool.splice(x,1);
            console.warn("Aborted "+x+" ajax calls");
        }

        alert(this.xhrPool.length+ " of "+xhrPoolLength+" calls aborted");
    }
}

var app = new MyApp();

There are always 40 calls at once. I have throttled the ajax calls so that non of the call responds anything for few minutes. i.e. status of all 40 calls remain pending for few minutes.

I have a button, upon clicking calls app.AbortAllAjaxCall(). app.AbortAllAjaxCall() method aborts the ajax calls in a loop and finally alerts the length of aborted calls of length of total ajax calls.

Problem

However, the problem is that, by clicking the button all of the ajax calls should have been aborted, but it does not. I have to click buton 3-4 times to abort all ajax calls.

Can anybody shed light on what I am doing wrong here?

Thanks

Upvotes: 0

Views: 197

Answers (1)

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

It's because you used splice so the index changed while looping. For example: when x is 0, you abort the first ajax and remove it from array so the element with index 1 will become the first and will not be aborted when x become 1. To solve this, you can loop from the end of array:

for (let x = this.xhrPool.length - 1; x >= 0; x--){
  this.xhrPool[x].abort();
  this.xhrPool.splice(x,1);
  console.warn("Aborted "+x+" ajax calls");
}

Or just set xhrPool to an empty array after aborting all the ajax without using splice:

for(x in this.xhrPool){
  this.xhrPool[x].abort();
  console.warn("Aborted "+x+" ajax calls");
}
this.xhrPool = [];

Upvotes: 1

Related Questions