Created
December 19, 2023 06:46
-
-
Save amr3k/74155aaa20763cdd4be89fcf7edd3a39 to your computer and use it in GitHub Desktop.
Javascript 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
/** | |
* Debounces a function by delaying its execution until a certain amount of time has passed without any further calls. | |
* @param {Function} func - The function to be debounced. | |
* @param {number} delay - The delay in milliseconds. | |
* @returns {Function} - The debounced function. | |
*/ | |
function debounce(func: Function, delay: number): Function { | |
let timeout: ReturnType<typeof setTimeout>; | |
return function (...args: any[]) { | |
clearTimeout(timeout); | |
timeout = setTimeout(() => func.apply(this, args), delay); | |
}; | |
} | |
let debouncedHandleSearch = debounce(handleSearch, 250); // Delay the search function call by 250ms | |
const inputElm = document.querySelector('input[type="search"]'); | |
inputElm.addEventListener('keydown', (e)=>{ | |
debouncedHandleSearch(e.target.value); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment