How to fire AJAX request Periodically?
Yes, you could use either the JavaScript setTimeout()
method or setInterval()
method to invoke the code that you would like to run. Here's how you might do it with setTimeout:
function executeQuery() {
$.ajax({
url: 'url/path/here',
success: function(data) {
// do something with the return value here if you like
}
});
setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}
$(document).ready(function() {
// run the first time; all subsequent calls will take care of themselves
setTimeout(executeQuery, 5000);
});
As others have pointed out setInterval and setTimeout will do the trick. I wanted to highlight a bit more advanced technique that I learned from this excellent video by Paul Irish: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/
For periodic tasks that might end up taking longer than the repeat interval (like an HTTP request on a slow connection) it's best not to use setInterval()
. If the first request hasn't completed and you start another one, you could end up in a situation where you have multiple requests that consume shared resources and starve each other. You can avoid this problem by waiting to schedule the next request until the last one has completed:
// Use a named immediately-invoked function expression.
(function worker() {
$.get('ajax/test.html', function(data) {
// Now that we've completed the request schedule the next one.
$('.result').html(data);
setTimeout(worker, 5000);
});
})();
For simplicity I used the success callback for scheduling. The down side of this is one failed request will stop updates. To avoid this you could use the complete callback instead:
(function worker() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 5000);
}
});
})();