Last active
December 25, 2015 20:09
-
-
Save fabioyamate/7032457 to your computer and use it in GitHub Desktop.
polling using jQuery deferred with timeout, similar to go channels
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
/* Performs a pooling with a timeout limit and throttle frequency. | |
fn - a function that returns a promise of an async computation | |
timeout - time in milliseconds to cancel pooling (default 10s) | |
throttle - the minimumm time between pollings | |
Use throttle if the async computation is too fast and you want | |
that occurrances happens in intervals. | |
*/ | |
var polling = function(fn, timeout, throttle) { | |
var expired = false; // guard | |
timeout = timeout || 10000; // default timeout of 10s | |
throttle = throttle || 1000; // 1s sample at least | |
return $.Deferred(function(dfd) { | |
// stop pooling if timeout | |
setTimeout(function() { | |
expired = true; | |
// we consider the deferred as completed | |
dfd.resolve(); | |
}, timeout); | |
// the pooler that will call the deferred function | |
var pooler = _.throttle(function() { | |
// TODO: the fn should be compliant with the done and progress? | |
fn().done(function(result) { | |
// once the async computation it need to inform if the job is complete | |
if (expired || result.complete) { | |
dfd.resolve(); | |
} else { | |
// notifies progress | |
dfd.notify(result.time); | |
} | |
}).always(function() { | |
if (!expired) { | |
pooler(); // recur | |
} | |
}); | |
}, throttle); | |
pooler(); // start pooler | |
return dfd.promise(); | |
}); | |
}; | |
polling(getQuote, 30000).progress(updateHtml).done(removeLoader); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment