Skip to content

Instantly share code, notes, and snippets.

@cabaalexander
Last active August 28, 2022 22:45
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 cabaalexander/6560a9e0439b40a7127e896203d40e1c to your computer and use it in GitHub Desktop.
Save cabaalexander/6560a9e0439b40a7127e896203d40e1c to your computer and use it in GitHub Desktop.
My take on the `debounce` function
/**
* Debounce
* This will create a function that can be called multiple times and only be
* executed once, within a threshold you speficy
* @param {function} callback Callback function to be executed
* @param {number} threshold Time to wait before executing the callback
* @return {function} The function that can be triggered multiple time
*/
function debounce(callback, threshold = 1000) {
// input validation
if (!callback || typeof callback !== 'function') {
return () => {}
}
// save previous timeout id on this closure (the magic)
let timeoutId = null
// end function
return () => {
// clear previous timeout
clearTimeout(timeoutId)
// create/execute new timeout
timeoutId = setTimeout(() => {
callback()
}, threshold)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment