Skip to content

Instantly share code, notes, and snippets.

@karlhorky
Created April 4, 2014 09:36
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 karlhorky/9971286 to your computer and use it in GitHub Desktop.
Save karlhorky/9971286 to your computer and use it in GitHub Desktop.
throttle through an AngularJS service. based on https://gist.github.com/mrgamer/6139485
angular.module("app").factory "throttle", [
"$timeout"
($timeout) ->
return (delay, no_trailing, callback, debounce_mode) ->
timeout_id = undefined
last_exec = 0
if typeof no_trailing isnt "boolean"
debounce_mode = callback
callback = no_trailing
no_trailing = undefined
wrapper = ->
that = this
elapsed = +new Date() - last_exec
args = arguments
exec = ->
last_exec = +new Date()
callback.apply that, args
return
clear = ->
timeout_id = undefined
return
exec() if debounce_mode and not timeout_id
$timeout.cancel timeout_id if timeout_id
if debounce_mode is undefined and elapsed > delay
exec()
else timeout_id = $timeout((if debounce_mode then clear else exec), (if debounce_mode is undefined then delay - elapsed else delay)) if no_trailing isnt true
return
wrapper
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment