Skip to content

Instantly share code, notes, and snippets.

@rdillmanCN
Created December 30, 2017 09:27
Show Gist options
  • Save rdillmanCN/6d43cc7800c2afa85d90ff57b8d3e408 to your computer and use it in GitHub Desktop.
Save rdillmanCN/6d43cc7800c2afa85d90ff57b8d3e408 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