Created
July 27, 2017 05:03
-
-
Save rdillmanCN/fa249287e42cf0987d33ef7e5aec04d7 to your computer and use it in GitHub Desktop.
Throttle
This file contains 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
/** | |
* Throttle functions. | |
* | |
* @param {Function} fn - The function to be throttled. | |
* @param {number} delay - The delay time in milliseconds. | |
* @param {Object|HTMLElement} scope - What this should be inside the function. | |
* @return {Function} - The throttled function wrapped with a new function. | |
*/ | |
function throttle(fn, delay, scope) { | |
delay = delay || 250; | |
var last; | |
var defer; | |
return function() { | |
var scope = scope || this; | |
var now = Date.now(); | |
var args = arguments; | |
function reset() { | |
clearTimeout(defer); | |
defer = setTimeout(function timed() { | |
last = now; | |
fn.apply(scope, args); | |
}, delay); | |
} | |
last && last + delay > now ? reset() : fn.apply(scope, args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment