Last active
January 10, 2018 12:07
-
-
Save colthreepv/6139485 to your computer and use it in GitHub Desktop.
throttle function for AngularJS.
Original one: https://github.com/cowboy/jquery-throttle-debounce
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('helperFunctions', []) | |
.factory('throttle', ['$timeout', function ($timeout) { | |
return function (delay, no_trailing, callback, debounce_mode) { | |
var timeout_id, | |
last_exec = 0; | |
if (typeof no_trailing !== 'boolean') { | |
debounce_mode = callback; | |
callback = no_trailing; | |
no_trailing = undefined; | |
} | |
var wrapper = function () { | |
var that = this, | |
elapsed = +new Date() - last_exec, | |
args = arguments, | |
exec = function () { | |
last_exec = +new Date(); | |
callback.apply(that, args); | |
}, | |
clear = function () { | |
timeout_id = undefined; | |
}; | |
if (debounce_mode && !timeout_id) { exec(); } | |
if (timeout_id) { $timeout.cancel(timeout_id); } | |
if (debounce_mode === undefined && elapsed > delay) { | |
exec(); | |
} else if (no_trailing !== true) { | |
timeout_id = $timeout(debounce_mode ? clear : exec, debounce_mode === undefined ? delay - elapsed : delay); | |
} | |
}; | |
return wrapper; | |
}; | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How do you init wrapper()?