Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Created August 20, 2013 10:50
Show Gist options
  • Select an option

  • Save CMCDragonkai/6279958 to your computer and use it in GitHub Desktop.

Select an option

Save CMCDragonkai/6279958 to your computer and use it in GitHub Desktop.
JS: AngularJS Debounced Function Factory. Relies on $timeout.
/**
* This creates a trailing debounced function. The callback will only be executed at the end
* of the specified delay. Repeated calls to the debounced function will cancel the previous
* call, and restart the delay. This is perfect for form inputs that you only want to act upon
* after the user stops entering characters.
* @param {Function} callback Callback to be executed when there is no more repeated calls to
* the debounced function and when the delay has counted down
* @param {Integer} delay Delay in milliseconds. This delay will be refreshed each time
* there is a repeated call to the throttled function
* @return {Function} Debounced function
*/
this.createDebouncedFunction = function(callback, delay){
var listOfIterations = [];
var prevIteration;
return function(){
prevIteration = listOfIterations.shift();
if(prevIteration){
$timeout.cancel(prevIteration);
}
listOfIterations.push($timeout(function(){
callback();
}, delay));
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment