I got onto these examples showing polling vs long-polling in javascript, however I do not understand how they differ from one another. Especially regarding the long polling example, how does it keep its connection open?
This is what the traditional polling scenario looks like:
(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);
})();
and this is the long polling example:
(function poll(){
$.ajax({ url: "server", success: function(data){
//Update your dashboard gauge
salesGauge.setValue(data.value);
}, dataType: "json", complete: poll, timeout: 30000 });
})();
Thanks!
The difference is this: long polling allows for some kind of event-driven notifying, so the server is able to actively send data to the client. Normal polling is a periodical checking for data to fetch, so to say. Wikipedia is quite detailed about that:
With long polling, the client requests information from the server in a way similar to a normal polling; however, if the server does not have any information available for the client, then instead of sending an empty response, the server holds the request and waits for information to become available (or for a suitable timeout event), after which a complete response is finally sent to the client.
Long polling reduces the amount of data that needs to be sent because the server only sends data when there really IS data, hence the client does not need to check at every interval x.
If you need a more performant (and imho more elegant) way of full duplex client/server communication, consider using the WebSocket protocol, it's great!