1

This is my ajax function

function repeatedCall() {    
    $.ajax({
        url: '/getUrl',
        complete: function(data) {   
            if (data.statusText != "error") {
                //my actions    
            }    
        }   
    })    
}

setInterval(repeatedCall, 5000); //To make repeated ajax calls

function updateData_function{   
     //I want to abort all previous ajax calls and make a new ajax call since it will update the data     
}

I can use clearInterval but the pending calls are not getting aborted and hence it is not updating properly.

How can i make repeated calls and at the same time abort all the requests if it enters my updateData_function.

This updateData_function will have new values so i need to make fresh ajax request.

How can i do this? Please help!! Thanks a lot in advance!!

Ramya S
  • 2,954
  • 5
  • 14
  • 24
  • This is a bit strange! why do you want to make ajax calls repeatedly? Is it that you'd like to make an ajax call, get the response and use values from the response for your next ajax request? – lshettyl Oct 07 '17 at 11:41
  • I need to refresh the table every 5 seconds..So i'm making calls repeatedly..@Ishettyl – Ramya S Oct 07 '17 at 11:43
  • Where would you call `updateData_function` and when? Moreover, making ajax in setInterval is not a good practise. You'd rather do a recursion based on the request in progress being complete. Hence, you'd never have a dead-lock condition where there are pending ajax requests! – lshettyl Oct 07 '17 at 11:44
  • @ishettyl Whenever someone enters a Url value in the table, I need to update the table with the new record. So that time this updateData_function will be called. After that when i'm refreshing the table i need the latest record also. So only i want to abort the previous calls and make a fresh ajax request. – Ramya S Oct 07 '17 at 11:47
  • This is what you may be after. Talk a [look at this answer](https://stackoverflow.com/a/4551178/572827) as a starting point. – lshettyl Oct 07 '17 at 11:59

3 Answers3

1

Using setInterval to make repetead calls is not a good practice. Assume that your previous request is not completed, then there is no point in making the same ajax call. Also, as you may know, there are possibility that the response from the previous ajax call can come after the recent ajax response. So it is always better to abort any previous ajax calls.

I think the below solutions may solve your issue:

Solution 1: Just Extentending what you have done:

var xhr

function repeatedCall() {
  if(xhr){
    // abort any previous calls, to avoid any inconsistency
    xhr.abort()
  }
  xhr = $.ajax({
    url: '/getUrl',
    complete: function(data) {
      if (data.statusText != "error") {
        //my actions
      }
    }
  })
}
setInterval(repeatedCall, 5000)
function updateData_function {
  //I want to abort all previous ajax calls and make a new ajax call since it will update the data 
  if(xhr){
    xhr.abort()
  }
}

Solution 2: What I feel is a better approach

var xhr;

function repeatedCall() {
  xhr = $.ajax({
    url: '/getUrl',
    complete: function(data) {
      if (data.statusText != "error") {
        //my actions
        // Call the ajax call again:
        setTimeout(repeatedCall, 5000)
      }
    }
  })
}

function updateData_function {
  //I want to abort all previous ajax calls and make a new ajax call since it will update the data 
  if(xhr){
    xhr.abort()
  }
  // do something
}
// somewhere - to initiate the repeatedCall for the first time
repeatedCall()
Sujeet Jaiswal
  • 1,071
  • 7
  • 12
  • You are not even sending request with settimeout. Because you say for example 500ms after fire it. If there is a new fire before 500ms it clear timeout and set another 500ms which means delay. – Güney Saramalı Oct 07 '17 at 12:14
  • for #2, once the previous request is complete, settimeout will initiate a new request after the given time. based on your average response time of the API, you can decide to manupulate the time. Just tom make things more clearer to you, i have added the last line , where for the first time you will initiate the call. – Sujeet Jaiswal Oct 07 '17 at 12:22
  • @SUJEETJAISWAL Thanks a lot for responding.. But if i declare xhr = $.ajax... It is not executing the ajax call ? – Ramya S Oct 07 '17 at 12:38
0

I faced the same problem before as well and I was sending to many ajax calls on keyup which was leading my website to collapse. I found out the solution to setTimeout(); in to the ajax all firing and keeping firing the function clears timeout and settimeout again. This let you to fire ajax only 1 time on pressing to many time.

Edit: Ok for example I had a searchbox which was getting predefined suggestions with ajax call with onkeyup function. as I was start typing it was firing ajax call again and again and stucking. I started to cancel the one before as I firing another so fixed the situation. Here is the DEMO Doesnt matter how many time you hit the button it fires only one.

Güney Saramalı
  • 791
  • 1
  • 10
  • 19
0

I've modified my code and this works

    abortValue = false;
    var xhr;
    xhrPool = [];
    var trying;

    function abortAjax() {
        $.each(xhrPool, function(idx, jqXHR) {
            jqXHR.abort();

        });

    }
    $(document).ready(function() {
        fn = function() {
            xhr = $.ajax({
                url: '/getUrl',
                beforeSend: function(jqXHR) {
                    xhrPool.push(jqXHR);
                },
                complete: function(jqXHR, data) {
                    if (abortValue == true) {
                        abortAjax()
                    } else {
                        if (jqXHR.statusText != "error" && "undefined") {
                            //myactions

                        }

                    }
                }
            });

        };

        var interval = setInterval(fn, 5000);
    });


    function updateData_function {
        //I want to abort all previous ajax calls and make a new ajax call since it will update the data

        abortValue = true;
        abortAjax();
        abortValue = false;
        fn();
}
Ramya S
  • 2,954
  • 5
  • 14
  • 24