Skip to content

Instantly share code, notes, and snippets.

@amoradi
Forked from jasdeepkhalsa/longPolling.js
Last active October 4, 2016 15:22
Show Gist options
  • Select an option

  • Save amoradi/1fb396f86b8df647e4d3e86f35364e1b to your computer and use it in GitHub Desktop.

Select an option

Save amoradi/1fb396f86b8df647e4d3e86f35364e1b to your computer and use it in GitHub Desktop.
Simple Long Polling Example with JavaScript and jQuery by Tian Davis (@tiandavis) from Techoctave.com (http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery)
// Long Polling (Recommened Technique - Creates An Open Connection To Server ∴ Fast)
(function poll(){
$.ajax({ url: "server", success: function(data){
//Update your dashboard gauge
salesGauge.setValue(data.value);
}, dataType: "json", complete: poll, timeout: 30000 });
})();
// uses window.setTimout instead of $.ajax's timeout to avoid FF edge case
// "In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout" - http://api.jquery.com/jquery.ajax/
(function poll() {
setTimeout(function() {
$.ajax({ url: "server", success: function(data) {
sales.setValue(data.value);
}, dataType: "json", complete: poll });
}, 30000);
})();
// The setTimeout Technique (Not Recommended - No Queues But New AJAX Request Each Time ∴ Slow)
(function poll(){
setTimeout(function(){
$.ajax({ url: "server", success: function(data){
//Update your dashboard gauge
salesGauge.setValue(data.value);
//Setup the next poll recursively
poll();
}, dataType: "json"});
}, 30000);
})();
// The setInterval Technique (Not Recommended - Creates Queues of Requests ∴ Can Be Slow)
setInterval(function(){
$.ajax({ url: "server", success: function(data){
//Update your dashboard gauge
salesGauge.setValue(data.value);
}, dataType: "json"});
}, 30000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment