Skip to content

Instantly share code, notes, and snippets.

@isthatcentered
Created November 18, 2017 15:44
Show Gist options
  • Save isthatcentered/b5fa657aa3ec90790d34f3c138b58839 to your computer and use it in GitHub Desktop.
Save isthatcentered/b5fa657aa3ec90790d34f3c138b58839 to your computer and use it in GitHub Desktop.
ES6 debounce function
/**
* 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