Last active
August 28, 2022 22:45
-
-
Save nicanordlc/6560a9e0439b40a7127e896203d40e1c to your computer and use it in GitHub Desktop.
My take on the `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 | |
* 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