Created
August 20, 2013 10:50
-
-
Save CMCDragonkai/6279958 to your computer and use it in GitHub Desktop.
JS: AngularJS Debounced Function Factory. Relies on $timeout.
This file contains hidden or 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
| /** | |
| * 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