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 hav
Instead of using setInterval
, call setTimeout()
in the AJAX completion callback to start each call 10 seconds after the previous one finishes.
instead of using setInterval, calculate the request time (usually using a unix timestamp in seconds), how much for 10 seconds, in the server side, use setTimeout
the remaining time, so it will vary from user to user, on their ping time (or the business of the site)
function heartbeat(){
$.ajax({
'url': '/where/',
'success': function(data){
setTimeout(heartbeat, parseInt(data) * 1000);
}
});
}
heartbeat(); // initialize it
in the server side, (like in PHP), you would do
<?php
// do your stuff
echo (time() - (int)$time_requested) + 10; // it will vary per user, so if it takes 2 second, it will be 12, if it returns imediately, returns 10
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);
}