Skip to content

Instantly share code, notes, and snippets.

@amr3k
Created December 19, 2023 06:46
Show Gist options
  • Save amr3k/74155aaa20763cdd4be89fcf7edd3a39 to your computer and use it in GitHub Desktop.
Save amr3k/74155aaa20763cdd4be89fcf7edd3a39 to your computer and use it in GitHub Desktop.
Javascript debounce function
/**
* 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