Skip to content

Instantly share code, notes, and snippets.

@night-fury-rider
Created May 16, 2025 03:17
Show Gist options
  • Save night-fury-rider/e8022c99b552c2b7899a77e5f02aeb72 to your computer and use it in GitHub Desktop.
Save night-fury-rider/e8022c99b552c2b7899a77e5f02aeb72 to your computer and use it in GitHub Desktop.
Performance - Debounce
// Make sure we have a input field with id "inputData" in our DOM.
const inputData = document.getElementById("inputData");
const getDataFromServer = (name) => {
console.log(`${name} :: getting Data from Server...........`);
};
const debounce = (callback, delay) => {
delay = delay || 2000;
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
callback(...args);
}, delay);
};
};
// Make sure you don't use debounce's direct call in the event listner
// Otherwise it will recreate the timeout eachtime and won't work as expected
const debouncedFunc = debounce(getDataFromServer);
inputData.addEventListener("input", (e) => {
const searchValue = e.target.value;
debouncedFunc(searchValue);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment