Skip to content

Instantly share code, notes, and snippets.

@rdillmanCN
Created July 27, 2017 05:03
Show Gist options
  • Save rdillmanCN/fa249287e42cf0987d33ef7e5aec04d7 to your computer and use it in GitHub Desktop.
Save rdillmanCN/fa249287e42cf0987d33ef7e5aec04d7 to your computer and use it in GitHub Desktop.
Throttle
/**
* 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