Skip to content

Instantly share code, notes, and snippets.

@RichardDillman
Created December 30, 2017 09:29
Show Gist options
  • Select an option

  • Save RichardDillman/8e71ee4f30943c422834e10ac3a79dd1 to your computer and use it in GitHub Desktop.

Select an option

Save RichardDillman/8e71ee4f30943c422834e10ac3a79dd1 to your computer and use it in GitHub Desktop.
Throttle function
/**
* 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