Skip to content

Instantly share code, notes, and snippets.

@kumavis
Last active December 15, 2015 14:09
Show Gist options
  • Save kumavis/5272343 to your computer and use it in GitHub Desktop.
Save kumavis/5272343 to your computer and use it in GitHub Desktop.
callMethod = (target, method, args) ->
method = target[method] if Ember.typeOf(method) is "string"
method.apply target, args
###
Returns a function, that, when invoked, will only be triggered at most once during a given window of time.
###
Ember.throttle = (target, method, wait) ->
timeout = undefined
throttling = undefined
more = undefined
result = undefined
whenDone = undefined
# detect method signature (adjust for optional arguments)
if Ember.typeOf(method) is "number"
wait = method
method = target
target = null
# build timer-reset function
whenDone = Ember.debounce(->
more = throttling = false
, wait)
# build throttling function wrapper
return ->
later = undefined
args = arguments
later = ->
timeout = null
callMethod target, method, args if more
whenDone()
timeout = setTimeout(later, wait) unless timeout
if throttling
more = true
else
result = callMethod(target, method, args)
whenDone()
throttling = true
result
###
Returns a function, that, as long as it continues to be invoked, will not be triggered.
The function will be called after it stops being called for N milliseconds.
If immediate is passed, trigger the function on the leading edge, instead of the trailing.
###
Ember.debounce = (target, method, wait, immediate) ->
timeout = undefined
# detect method signature (adjust for optional arguments)
if Ember.typeOf(method) is "number"
immediate = wait
wait = method
method = target
target = null
# build debouncing function wrapper
return ->
args = arguments
later = ->
timeout = null
callMethod target, method, args unless immediate
callMethod target, method, args if immediate and not timeout
clearTimeout timeout
timeout = setTimeout(later, wait)
###
Returns a function, that, as long as it continues to be invoked, will not be triggered.
The function will be called after it stops being called for N milliseconds.
If immediate is passed, trigger the function on the leading edge, instead of the trailing.
###
Ember.debounce = (target, method, wait, immediate) ->
timeout = undefined
# detect method signature (adjust for optional arguments)
if Ember.typeOf(method) is "number"
immediate = wait
wait = method
method = target
target = null
# build debouncing function wrapper
return ->
args = arguments
later = ->
timeout = null
callMethod target, method, args unless immediate
callMethod target, method, args if immediate and not timeout
clearTimeout timeout
timeout = setTimeout(later, wait)
@kumavis
Copy link
Author

kumavis commented Mar 29, 2013

confirmed to work in Ember 1.0.0-rc.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment