Created
February 13, 2012 16:56
-
-
Save joeytwiddle/1818255 to your computer and use it in GitHub Desktop.
callbackWithFallback
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
# Takes: a callback function and a fallback function | |
# Returns: a callback function. | |
# Also: sets up a timeout, so that if the callback function is not called, the fallback function will be run | |
callbackWithFallback = (callback, fallback, waitSeconds) -> | |
waitSeconds = waitSeconds || 15 | |
callbackHappened = false | |
robustCallback = () -> | |
if callbackHappened | |
console.warn "Waited so long to call "+getSimpleFunctionString(callback)+" that we called the fallback "+getSimpleFunctionString(fallback) | |
return # Don't call the callback if we've already called the fallback | |
callbackHappened = true | |
callback.apply(this,arguments) | |
checkForFailure = () -> | |
if !callbackHappened | |
console.log "Callback did not happen within assigned time. Calling fallback." | |
callbackHappened = true | |
fallback() | |
setTimeout checkForFailure, waitSeconds*1000 | |
return robustCallback # Use this immediately! | |
# CONSIDER: Should our scripts assume the existence of console.warn() or just | |
# warn()? We can implement either of them! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment