Skip to content

Instantly share code, notes, and snippets.

@joeytwiddle
Created February 13, 2012 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeytwiddle/1818255 to your computer and use it in GitHub Desktop.
Save joeytwiddle/1818255 to your computer and use it in GitHub Desktop.
callbackWithFallback
# 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