Created
November 27, 2013 19:21
-
-
Save six8/7681539 to your computer and use it in GitHub Desktop.
A debounce that you can cancel
This file contains hidden or 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
### | |
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