Last active
August 29, 2015 14:06
-
-
Save jacob414/54f495c2d8f184cedc95 to your computer and use it in GitHub Desktop.
backing-off.coffee
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
# Re-try function with exponential back-off time | |
# `max`: Maximum amount of attempts | |
# `wait`: Wait time between attemps, in milliseconds | |
# `attempt`: Function to make one attempt, accepts arguments <nth try>, <callback upon success> | |
gently = @gently = (max, wait, attempt) -> | |
new Promise (fulfill, fail) -> | |
recur = (max, wait, attempt, n) -> | |
pending = setTimeout (-> | |
if n is max | |
clearTimeout pending | |
fail n | |
else recur max, 2*wait, attempt, n+1 | |
), wait | |
attempt n, -> | |
clearTimeout pending | |
fulfill n | |
recur max, wait, attempt, 1 | |
@tryit = (attempts) -> | |
attempt = (n, done) -> | |
if n is attempts then done() | |
else console.log "My hypothetical request no #{n}..." | |
# Try it maximum 4 times with initial wait time of 130ms: | |
gently(4, 130, attempt).then( | |
((n) -> console.log " ..succeeded on attempt #{n}"), | |
((n) -> console.log " ..failed after attempt #{n}") ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment