Skip to content

Instantly share code, notes, and snippets.

@hendrysadrak
Created October 25, 2016 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hendrysadrak/d00482e7989b8f43b230d9e00a01e5c2 to your computer and use it in GitHub Desktop.
Save hendrysadrak/d00482e7989b8f43b230d9e00a01e5c2 to your computer and use it in GitHub Desktop.
ES6 Throttle implementation with arguments and context
/**
* Simple ES6 Throttle implementation with arguments and context
*
* @param callback {Function} - Function to throttle
* @param [limit=30] {number} - Ms to throttle
* @param [context=this] - Context to run in
* @return {Function}
*/
const throttle = ( callback, limit = 30, context = this ) => {
let
wait = false,
timeout;
return ( ...args ) => {
if ( !wait ) {
callback.call( context, ...args );
wait = true;
clearTimeout( timeout );
timeout = setTimeout( function () {
wait = false;
}, limit );
}
}
};
// Usage:
function funcToThrottle() {
console.log('Woop!');
}
window.addEventListener("scroll", throttle(funcToThrottle, 100));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment