Created
October 16, 2014 23:40
-
-
Save bcole808/c0c6877a53c59a77119f to your computer and use it in GitHub Desktop.
Throttle Javascript Functions
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
/** | |
* Debounce a function so that it will only fire once | |
* | |
* USAGE EXAMPLE: | |
* $scope.search = debounce(performSearch, 500); // Bind to ng-keyup | |
* | |
* http://davidwalsh.name/javascript-debounce-function | |
* | |
* @param func [Function] - The function to execute | |
* @param wait [int] - How many milliseconds to debounce | |
* @param immediate [boolean] - If true, fires at the leading edge | |
* @return [Function] | |
*/ | |
function debounce (func, wait, immediate) { | |
var timeout; | |
return function() { | |
var context = this, args = arguments; | |
var later = function() { | |
timeout = null; | |
if (!immediate) func.apply(context, args); | |
}; | |
var callNow = immediate && !timeout; | |
clearTimeout(timeout); | |
timeout = setTimeout(later, wait); | |
if (callNow) func.apply(context, args); | |
}; | |
}; | |
/** | |
* Throttle a function so that it will not exceed a specified rate | |
* | |
* USAGE EXAMPLE: | |
* $scope.search = throttle(performSearch, 500); // Bind to ng-keyup | |
* | |
* http://scn.sap.com/community/labs/blog/2014/04/30/debounce-and-throttle-in-javascript | |
* | |
* @param func [Function] - The function to execute | |
* @param wait [int] - How many milliseconds to debounce | |
* @param options [object] | |
* @return [Function] | |
*/ | |
function throttle (func, wait, options) { | |
var context, args, result; | |
var timeout = null; | |
var previous = 0; | |
options || (options = {}); | |
var later = function() { | |
previous = options.leading === false ? 0 : _.now(); | |
timeout = null; | |
result = func.apply(context, args); | |
context = args = null; | |
}; | |
return function() { | |
var now = _.now(); | |
if (!previous && options.leading === false) previous = now; | |
var remaining = wait - (now - previous); | |
context = this; | |
args = arguments; | |
if (remaining <= 0) { | |
clearTimeout(timeout); | |
timeout = null; | |
previous = now; | |
result = func.apply(context, args); | |
context = args = null; | |
} else if (!timeout && options.trailing !== false) { | |
timeout = setTimeout(later, remaining); | |
} | |
return result; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment