Skip to content

Instantly share code, notes, and snippets.

@nicanordlc
Last active August 28, 2022 22:45
Show Gist options
  • Save nicanordlc/6560a9e0439b40a7127e896203d40e1c to your computer and use it in GitHub Desktop.
Save nicanordlc/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