Last active
October 24, 2022 13:27
-
-
Save treyhuffine/d628c0cd2e7d25f829159e08c29e92c0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Originally inspired by David Walsh (https://davidwalsh.name/javascript-debounce-function) | |
// Returns a function, that, as long as it continues to be invoked, will not | |
// be triggered. The function will be called after it stops being called for | |
// `wait` milliseconds. | |
const debounce = (func, wait) => { | |
let timeout; | |
// This is the function that is returned and will be executed many times | |
// We spread (...args) to capture any number of parameters we want to pass | |
return function executedFunction(...args) { | |
// The callback function to be executed after | |
// the debounce time has elapsed | |
const later = () => { | |
// null timeout to indicate the debounce ended | |
timeout = null; | |
// Execute the callback | |
func(...args); | |
}; | |
// This will reset the waiting every function execution. | |
// This is the step that prevents the function from | |
// being executed because it will never reach the | |
// inside of the previous setTimeout | |
clearTimeout(timeout); | |
// Restart the debounce waiting period. | |
// setTimeout returns a truthy value (it differs in web vs Node) | |
timeout = setTimeout(later, wait); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
question
ref
https://levelup.gitconnected.com/debounce-in-javascript-improve-your-applications-performance-5b01855e086