Skip to content

Instantly share code, notes, and snippets.

@six8
Created November 27, 2013 19:21
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 six8/7681539 to your computer and use it in GitHub Desktop.
Save six8/7681539 to your computer and use it in GitHub Desktop.
A debounce that you can cancel
###
Creates a function that will delay the execution of `func` until after
`wait` milliseconds have elapsed since the last time it was invoked. Pass
`true` for `start` to cause debounce to invoke `func` on the leading edge
of the `wait` timeout. Subsequent calls to the debounced function will
return the result of the last `func` call.
###
debounce = (opt, func) ->
if typeof opt is 'number'
opt = {wait: opt}
opt or= {}
opt.start or= false # Call function on start
opt.wait or= 100
if typeof opt.start is 'boolean' and opt.start
opt.start = func
if func
opt.end = func # Call function at end
args = null
result = null
thisArg = null
timer = null
debouncer = ->
args = arguments
isStart = not timer
thisArg = @
if timer
clearTimeout(timer)
timer = setTimeout((->
timer = null
if opt.end
result = opt.end.apply(thisArg, args)
return
), opt.wait)
if isStart and opt.start
result = opt.start.apply(thisArg, args)
return result
debouncer.cancel = ->
clearTimeout(timer) if timer
timer = null
return debouncer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment