Created
November 18, 2017 15:44
-
-
Save isthatcentered/b5fa657aa3ec90790d34f3c138b58839 to your computer and use it in GitHub Desktop.
ES6 debounce function
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
/** | |
* debounce | |
* Ensures a function won't be called before a defined amout of time | |
* Ex: | |
* on window resize, ensure a function won't be called | |
* until the user stopped resizing window for {time param} | |
* | |
* @param { function } fn Callback to be executed after debounce | |
* @param { int } time Time to wait before function execution | |
* @return {function(...[*])} | |
*/ | |
const debounce = ( fn, time = 300 ) => { | |
// Store active timeout | |
let timeout | |
return ( ...args ) => { | |
// Clear active timeout to prevent fn execution | |
clearTimeout( timeout ) | |
// Start a new timeout | |
timeout = setTimeout( fn.bind( null, ...args ), time ) | |
} | |
} | |
export default debounce |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment