Created
May 16, 2025 03:30
-
-
Save night-fury-rider/49951767fa3fc76467cadfb9e0c79e7e to your computer and use it in GitHub Desktop.
Performance - Throttling
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
// 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