Created
July 25, 2014 05:57
-
-
Save java-tester-x/d4a9ec29165e14e58cc3 to your computer and use it in GitHub Desktop.
jquery_traditional_polling_2_ways.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Traditional Polling | |
*/ | |
// (1) 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. | |
// (2) 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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment