admin管理员组

文章数量:1389859

If I want to implement short polling like this:

function firstCall(){
   $.ajax({
     ...
     success: function(response){
         if (response.OK == "OK"){
              secondCall();
         }else{
            firstCall();
         }
     }
  });

}

Will this be enough? or do I really need to surround the firstCall() in else clause with setTimeout ?Thanks

If I want to implement short polling like this:

function firstCall(){
   $.ajax({
     ...
     success: function(response){
         if (response.OK == "OK"){
              secondCall();
         }else{
            firstCall();
         }
     }
  });

}

Will this be enough? or do I really need to surround the firstCall() in else clause with setTimeout ?Thanks

Share Improve this question asked Aug 8, 2012 at 13:52 user1012451user1012451 3,4337 gold badges31 silver badges33 bronze badges 4
  • 6 How hard do you want to hit your server? This could result in 10+ requests per second. Also, you should handle AJAX errors. – josh3736 Commented Aug 8, 2012 at 13:54
  • 1 There are so many good alternatives to this kind of aggressive "are we there yet?" polling. Is this really your only option? – James M Commented Aug 8, 2012 at 13:59
  • Oh geesh. Thanks for pointing out. SO obvious. @JamesMcLaughlin Mind to share? – user1012451 Commented Aug 8, 2012 at 14:00
  • 1 Comet/long-polling, websockets, ... – James M Commented Aug 8, 2012 at 14:00
Add a ment  | 

4 Answers 4

Reset to default 5

I remend you to use a little timeout, because now you are creating a lot of traffic to your server. Ajax is fast and success will be executed very often.

So I remend you to use setTimeout or setInterval instead!

This solution relies on the first call to be a success. If at any point in time your code doesn't "succeed" (perhaps there was a server hiccup?), your "polling" will stop until a page refresh.

You could use setInterval to call that method on a defined interval, which avoids this problem:

setInterval(function(){
    $.ajax({}); // Your ajax here
}, 1000);

With both solutions, your server will be handling a lot of requests it might not need to. You can use a library like PollJS (shameless self plug) to add increasing delays, which will increase performance and decrease bandwidth:

// Start a poller
Poll.start({
    name: "example_poller",
    interval: 1000,
    increment: 200,
    action: function(){
        $.ajax({}); // Your ajax here
    }
});

// If you want to stop it, just use the name
Poll.stop("example_poller");

You need setTimeout() if you want to reduce requests to server

you'll need to setTimeout if you don't want to wait to user action or ajax response to trigger an event after a certain time, otherwise you may do wait for the ajax call success or error events.

本文标签: javascriptDo we need setTimeout for short pollingStack Overflow