Skip to content

Instantly share code, notes, and snippets.

@kingster
Forked from defunkt/gist:158493
Last active December 23, 2020 05:38
Show Gist options
  • Save kingster/6317997 to your computer and use it in GitHub Desktop.
Save kingster/6317997 to your computer and use it in GitHub Desktop.
Jquery Smart Poller with Stop Support
/*
* a smart poller for jquery.
* (by github)
*
* simple example:
*
* $.smartPoller(function(retry) {
* $.getJSON(url, function(data) {
* if (data) {
* doSomething(data)
* } else {
* retry()
* }
* })
* })
*
* With Timer Support
* var timer = { id : 0 }
* $.smartPoller(function(retry) {
* $.getJSON(url, function(data) {
* if (data) {
* doSomething(data)
* } else {
* retry()
* }
* })
* } , timer)
* Now anytime later u can cancell this smartpoller by doing
* clearTimeout (timer.id)
*
*
* The $.smartPoller function accepts a starting
* interval in ms but defaults to 1000:
*
* $.smartPoller(2000, function(retry) {
*
*/
;(function($) {
$.smartPoller = function(wait, pollerFunc, pollerID) {
if ($.isFunction(wait)) {
pollerID = pollerFunc
pollerFunc = wait
wait = 1000
}
if(pollerID == null ){
var pollerID = { id : null }
}
(function startPoller() {
pollerID.id = setTimeout(function() {
pollerFunc.call(this, startPoller)
}, wait)
wait = wait * 1.5
})()
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment