Last active
December 19, 2015 09:09
-
-
Save wulftone/5930730 to your computer and use it in GitHub Desktop.
A simple debouncing function that only executes the function after all input has stopped. http://blog.gaslight.co/page/3
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
### | |
source: http://blog.gaslight.co/page/3 | |
Debounce a function so it only executes once, after all inputs to it have ended, or after | |
a specified timeout interval. Optionally pass another argument to your debounced function | |
to execute it immediately, for example: `myDebouncedFunction( some, arguments, { now: true } )` | |
@example An Ember.js controller example usage | |
App.DocumentController = Ember.ObjectController.extend | |
autoSave: (-> | |
@debouncedSave() | |
).observes 'content.body' | |
debouncedSave: App.debounce ( -> @save() ), 1000 | |
save: -> | |
@get('store').commit() | |
@param func [Function] A function you want to "call later" | |
@param wait [Number] An integer number of milliseconds to wait before calling the function | |
@return [Function] The debounced version of the original function | |
### | |
App.debounce = (func, wait) -> | |
timeout = null | |
-> | |
args = arguments | |
lastArg = args[args.length - 1] | |
immediate = lastArg && lastArg.now | |
later = => | |
timeout = null | |
func.apply @, args | |
clearTimeout timeout | |
if immediate | |
func.apply @, args | |
else | |
timeout = setTimeout later, wait |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment