Skip to content

Instantly share code, notes, and snippets.

@colthreepv
Last active January 10, 2018 12:07
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save colthreepv/6139485 to your computer and use it in GitHub Desktop.
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
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;
};
}]);
@hackdan
Copy link

hackdan commented Dec 31, 2013

example ?

@aradnom
Copy link

aradnom commented Feb 2, 2014

Example of throttled scroll event:
var App = angular.module( 'MyApp', [ 'ngRoute', 'helperFunctions' ] );

App.directive( 'adnmScroll', [ '$window', 'throttle', function ( $window, throttle ) {
return function( scope, elm, attrs ) {
var throttled = throttle( 500, function () {
console.log( "I'm throttled." );
});
angular.element( $window ).bind( "scroll", throttled );
};
}]);

@amcdnl
Copy link

amcdnl commented Feb 26, 2014

I think you need to init wrapper() ... not working for me unless I do that.

@evgeniikozhanov
Copy link

Thanks! It's work for me!

@tomsommer
Copy link

How do you init wrapper()?

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