Created
May 3, 2012 02:57
-
-
Save fauxparse/2582692 to your computer and use it in GitHub Desktop.
Easy polling in jQuery
This file contains 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
$.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); } | |
}); |
This file contains 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
(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