Skip to content

Instantly share code, notes, and snippets.

@baldore
Created February 14, 2017 20:24
Show Gist options
  • Save baldore/cea3d6e8ab5cd0cca753e95c2d0a0b7a to your computer and use it in GitHub Desktop.
Save baldore/cea3d6e8ab5cd0cca753e95c2d0a0b7a to your computer and use it in GitHub Desktop.
Throttle
/**
* Creates and returns a new, throttled version of the passed function,
* that, when invoked repeatedly, will only actually call the original
* function at most once per every wait milliseconds.
*
* @param {function} func
* @param {number} threshold
* @param {object} [scope] custom this
* @returns {function} throttled function
*/
export function throttle(func, threshold, scope) {
const FUNC_ERROR_TEXT = 'First parameter must be a function.';
let last;
let deferTimer;
if (typeof func !== 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return function throttled(...args) {
const context = this || scope;
const now = +new Date();
if (last && now < last + threshold) {
clearTimeout(deferTimer);
deferTimer = setTimeout(() => {
last = now;
func.apply(context, args);
}, threshold);
} else {
last = now;
func.apply(context, args);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment