Skip to content

Instantly share code, notes, and snippets.

@jasdeepkhalsa
Last active October 8, 2020 14:32
Show Gist options
  • Save jasdeepkhalsa/4353139 to your computer and use it in GitHub Desktop.
Save jasdeepkhalsa/4353139 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 });
})();
// 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);
@RishiPrakash
Copy link

the first long polling method, won't it create more than one connections?

@kai101
Copy link

kai101 commented Jun 28, 2016

@RishiPrakash It will start another connection once the previous one completed.

@funkytaco
Copy link

But this still takes 30 seconds to fire the first time.

@remzmike
Copy link

No it doesn't take 30 seconds to fire the first time. It fires when the server says the connection is complete, which it will do when it notices the gauge value has changed on the server-side. At which point the client will immediately send another request, again waiting up to 30 seconds for a complete response from the server. The server doesn't necessarily respond to the requests immediately. It responds to them when the server-side logic dictates. So, the server is actually waiting to do something for the client, and the client is waiting for this to happen. That's why you usually need special servers, because many servers are not designed with this use case in mind, and even those that are probably got that way as a side effect of trying to scale through asynchronous i/o.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment