最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How long polling works - Stack Overflow

programmeradmin2浏览0评论

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..

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..

Share Improve this question edited Nov 24, 2016 at 15:55 Adil Shaikh 44.7k17 gold badges95 silver badges112 bronze badges asked Mar 30, 2013 at 22:09 spiralspiral 1013 silver badges11 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 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

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.

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.

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.

发布评论

评论列表(0)

  1. 暂无评论