Created
April 4, 2014 09:36
-
-
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
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
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