Skip to content

Instantly share code, notes, and snippets.

@bullgare
Last active January 2, 2016 11:49
Show Gist options
  • Save bullgare/61058663e0230461b51d to your computer and use it in GitHub Desktop.
Save bullgare/61058663e0230461b51d to your computer and use it in GitHub Desktop.
/**
* Throttling callbacks with specified delay.
* inspired by @link http://benalman.com/projects/jquery-throttle-debounce-plugin/
*/
.factory('Throttle', ['$rootScope', function throttle($rootScope)
{
var allTimeouts = {};
$rootScope.$on('$routeChangeStart', function() {
for (var i in allTimeouts) {
clearTimeout(allTimeouts[i]);
}
allTimeouts = {};
});
/**
* noTrailing is to prevent execution one last time after all invokation stopped
*/
return function (delay, noTrailing, $scope, callback) {
var unique = Math.round(Math.random() * 1e15),
timeoutId,
lastExec = 0;
if (typeof noTrailing != 'boolean')
{
callback = $scope;
$scope = noTrailing;
noTrailing = undefined;
}
// this wrapper will be invoked by consumers
function wrapper()
{
var me = this,
elapsed = (+new Date) - lastExec,
args = arguments;
timeoutId && clearTimer();
if (elapsed > delay) {
exec();
}
else if (! noTrailing)
{
timeoutId = setTimeout(function () {exec()}, delay - elapsed);
storeTimer();
}
// Executing given function
function exec()
{
lastExec = +new Date;
clearTimer();
callback.apply(me, args);
if (! $scope.$$phase) {
$scope.$digest();
}
}
function storeTimer()
{
allTimeouts[unique] = timeoutId;
}
function clearTimer()
{
clearTimeout(timeoutId);
allTimeouts[unique] = timeoutId;
}
}
return wrapper;
};
}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment