Created
October 25, 2016 13:17
-
-
Save hendrysadrak/d00482e7989b8f43b230d9e00a01e5c2 to your computer and use it in GitHub Desktop.
ES6 Throttle implementation with arguments and context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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