Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

RishiPrakash commented Apr 27, 2015

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

@kai101

This comment has been minimized.

Copy link

kai101 commented Jun 28, 2016

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

@funkytaco

This comment has been minimized.

Copy link

funkytaco commented Jul 24, 2016

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

@remzmike

This comment has been minimized.

Copy link

remzmike commented Feb 25, 2017

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
You can’t perform that action at this time.