Skip to content

Instantly share code, notes, and snippets.

@yushine
Forked from ksdev-pl/polling.md
Created October 26, 2016 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yushine/df2e45ba22304ea6d0eed532c34c9749 to your computer and use it in GitHub Desktop.
Save yushine/df2e45ba22304ea6d0eed532c34c9749 to your computer and use it in GitHub Desktop.
Polling (setInterval, setTimeout) #js

The setInterval Technique

Now, if you needed to poll your web service, your first instinct might be to do something like this with JavaScript and jQuery:

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

Here, we have the poll ready to execute every thirty (30) seconds. This code is pretty good. It's clean and asynchronous. You're feeling confident. Things will work (and they will), but with a catch. What if it takes longer than thirty (30) seconds for the server to return your call?

That's the gamble with using setInterval. Lag, an unresponsive server or a whole host of network issues could prevent the call from returning in its allotted time. At this point, you could end up with a bunch of queued Ajax requests that won't necessarily return in the same order.

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.

As you can see, jQuery's Ajax call can take as long as it wants to. So, this pattern doesn't guarantee execution on a fixed interval per se. But, it does guarantee that the previous interval has completed before the next interval is called.

Both techniques suffer from the same flaw - a new connection to the server must be opened each time the $.ajax method is called. To make that connection, your realtime app must gear up and battle through hoards of competing network traffic to make it to your server.

http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment