Here's a (archive.org mirror of a) helpful article on long polling (long-held HTTP request) using jQuery. A code snippet derived from this article:
(function poll() {
setTimeout(function() {
$.ajax({
url: "/server/api/function",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json",
complete: poll,
timeout: 2000
})
}, 5000);
})();
This will make the next request only after the ajax request has completed.
A variation on the above that will execute immediately the first time it is called before honouring the wait/timeout interval.
(function poll() {
$.ajax({
url: "/server/api/function",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json",
complete: setTimeout(function() {poll()}, 5000),
timeout: 2000
})
})();
setTimeout
and some have usedsetInterval
. Why would one be preferred to another? – Pneumo