Skip to content

Instantly share code, notes, and snippets.

@fauxparse
Created May 3, 2012 02:57
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 fauxparse/2582692 to your computer and use it in GitHub Desktop.
Save fauxparse/2582692 to your computer and use it in GitHub Desktop.
Easy polling in jQuery
$.poll({
url: '/status.json'
, dataType: 'json'
, timeout: 1000 // initial timeout of 1s
, multiplier: 2 // double the timeout each time
, retries: 10 // maximum of ten tries
, until: function(data) { return data.status == 'done'; }
, success: function(data) { alert(data.message); }
});
(function() {
$.poll = function(options) {
options = options || {};
var timeout = options.timeout || 5000,
maxTimeout = options.maxTimeout || 30000,
multiplier = options.multiplier || 1,
retries = options.retries || -1, // retry indefinitely
callback = options.until;
var f = function() {
$.ajax($.extend({}, options, {
success: function() {
if (callback && callback.apply(this, arguments)) {
options.success && options.success.apply(this, arguments);
} else if (retries) {
setTimeout(f, timeout);
timeout = Math.min(timeout * multiplier, maxTimeout);
retries -= 1;
}
}
}));
}
f();
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment