4

I am studying the ajax long polling but I am confused. what is different in traditional ajax calls and long polling

   var lpOnComplete = function(response) {
   alert(response);
   // do more processing
   lpStart();
  };

    var lpStart = function() {
    $.post('/path/to/script', {}, lpOnComplete, 'json');
    };

    $(document).ready(lpStart);

this example is just calling in recursive manner to the server.. what is different than the traditional call in setInterval..

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
spiral
  • 101
  • 3
  • 11

4 Answers4

10

As the name suggest Long Polling means polling something for a long time.

$.post('/path/to/script', {}, lpOnComplete, 'json');

Here is what the actual process starts, You make an ajax call to some script on server, in this case its /path/to/script , You need to make your server script(php for example) smart enough so that it only respond to request's when required data is available, the script should wait for a specified time period(for example 1 minute) and if no data available upto 1 minute then it should return without data.

As soon as server return something, in your callback function you again make an ajax call to the same script and the server script again continues the process.

Consider a chat application, In conventional way you are polling the server say every 2 second's and the server return's even if no messages are available.If upto one minute server get's no new messages for you, you end up hitting the server 30 times in last one minute.

Now consider Long Polling way, you set your server script to wait for one minute for the new messages. From the client, you make a single ajax call to your script and say no messages are arriving for next one minute, server will not respond until 1 minute. And you have hit the server just one time in last 1 minute. Can you imagine 30 Hit Vs 1 Hit

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
  • hmmmm... that is nice but this is like waiting for thirty days for some event to occur in the near by village .. though you can return home and go back after 29 days.. lol... Though I liked your explaination perfectly makes sense.. – spiral Mar 31 '13 at 08:06
4

In theory with setinterval, you could have overlapping processing,

so if one oncomplete handler takes particularly long, it may overlap with the next call, slowing down your system or resolving in unpredictable ways.

by explicitly starting the next poll after the first one has completed, you get less regular calls with the advantage that you're guaranteed to only doing as one unit of work at a time as a byproduct.

Hayk Saakian
  • 2,036
  • 2
  • 18
  • 31
  • what is the completion criteria for the long polling?? – spiral Mar 30 '13 at 22:17
  • and what is the exactly the push here. I think and see it is still the pull.. client is initiating and pulling server is not pushing without the client request??? – spiral Mar 30 '13 at 22:21
  • @AzamKhan simple answer is can't push from server to http protocol – charlietfl Mar 30 '13 at 22:22
  • @charlietfl Yes that is what confused me .. the term is confusing.. when I saw it got me hooked .. Can I do this?? really .. however, I don't see any worthy difference – spiral Mar 30 '13 at 22:29
  • I am trying to see ajax activity on stackoverflow and facebook chrome console but there is silence no activity so how they are doing things there? – spiral Mar 30 '13 at 22:31
  • @AzamKhan i refuse to go to facebook...but plenty of ajax on SO – charlietfl Mar 30 '13 at 22:34
  • I don't see any activity in chrome console window for stackoverflow.. how to find it.. I am dying to see it. – spiral Mar 30 '13 at 22:37
  • @AzamKhan i use firebug mostly, but should see activity in network tab in chrome. Hover over your user name for example to get dropdown to appear. or go to main page to see `xx new questions` show up, or clcik on a vote – charlietfl Mar 30 '13 at 23:17
  • 1
    @AzamKhan: Stack Overflow uses WebSockets. – icktoofay Mar 31 '13 at 05:22
  • @spiral it's actually a push since that push happens during an open connection. With short pulling, the client nags the server for infos. With long polling, the client 'attempts' to nag the server, but the server holds onto the connection for longer in hopes that something will happen during that hang. If something happens, like new info becomes available, it is then pushed down. So it originates as a pull, but when the data isn't immediately available, instead of saying "I got nothing, ask me again in 100ms," it says "I got nothing yet, but sit tight for another minute." It's a faked push. – Sinaesthetic Nov 22 '13 at 15:47
2

There are two ways to do long polling

  1. The setInterval Technique
 


     setInterval(function() {
      $.ajax({
        url: "server",
        success: function(data) {
          //Update your dashboard gauge
          salesGauge.setValue(data.value);
        },
        dataType: "json"
      });
    }, 30000);

  1. The setTimeout Technique

If you find yourself in a situation where you’re going to bust your interval time, then a recursive setTimeout pattern is recommend:




    (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);
    })();

Using the Closure technique, poll becomes a self executing JavaScript function that runs the first time automatically. Sets up the thirty (30) second interval. Makes the asynchronous Ajax call to your server. Then, finally, sets up the next poll recursively.

1

With long polling the server does not return unless data is ready, otherwise it holds the network connection open until data is ready, at which stage it can "push" to client as client is already waiting. Wikipedia has a good explanation. http://en.wikipedia.org/wiki/Long_polling#Long_polling. In your example, lponcomplete might not be called for many minutes.

Using constant settimeout type polling means that data that is ready immediately after your first request completes will not be delivered until your next poll, as the server as no connection to the client.

For the server, long polling keeps a socket open for long periods, tying up resource, while repeated short polling causes more network traffic.

Html5 has new stuff coming like websockets to help in this area too, so you might want to read about that also.

rlb
  • 1,674
  • 13
  • 18
  • Thanks.. Html5 is messy.. and browsers are not fully compatible with it.. I read a little about it. some about the Microsoft new model whatever I don't remember its name. – spiral Mar 30 '13 at 22:45
  • 3
    check out socket.io which is websockets + a polyfill for browsers that don't support it – Hayk Saakian Mar 31 '13 at 01:30