Skip to content

Instantly share code, notes, and snippets.

@night-fury-rider
Created May 16, 2025 03:30
Show Gist options
  • Save night-fury-rider/49951767fa3fc76467cadfb9e0c79e7e to your computer and use it in GitHub Desktop.
Save night-fury-rider/49951767fa3fc76467cadfb9e0c79e7e to your computer and use it in GitHub Desktop.
Performance - Throttling
// 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 throttle = (callback, delay) => {
delay = delay || 2000;
let isEnabled = true;
return (...args) => {
if (isEnabled) {
isEnabled = false;
setTimeout(() => {
callback(...args);
isEnabled = true;
}, delay);
}
};
};
// Make sure you don't use throttle's direct call in the event listner
// Otherwise it will recreate the timeout each time and won't work as expected
const throttledFunc = throttle(getDataFromServer);
inputData.addEventListener("input", (e) => {
const searchValue = e.target.value;
throttledFunc(searchValue);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment