Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax Heartbeat using setInterval, Preventing multiple calls at the same time

I wish to make an AJAX call using jQuery as a "heartbeat" in the background so that my web application can check for new data. For example every 10 seconds.

I have seen on other posts that it is possible to use setInterval() to call a method which does the call every X number of milliseconds.

However, what happens if my AJAX call takes more than 10 seconds? I still want it to complete the last request and I don't want another call to be instigated when there is already one in progress. This could result in the same information being placed on to the page twice!

What is the way to implement this for my method to wait for the original AJAX call to be completed, rather than simply "every 10 seconds", when the original one may not already be complete.

like image 746
Luke Avatar asked Dec 06 '12 17:12

Luke


1 Answers

try setting another timeout from your ajax success function:

function poll() {
    setTimeout( function() {
        $.ajax(.......).success( function(data) {
            poll();  //call your function again after successfully calling the first time.
        });
    }, 10000);
}
like image 108
bluetoft Avatar answered Sep 23 '22 21:09

bluetoft