-
Notifications
You must be signed in to change notification settings - Fork 0
41 Debouncing
Biswajit Sundara edited this page Aug 18, 2023
·
3 revisions
Debouncing is a technique to control the frequency at which a function is executed when it's triggered repeatedly.
- It involves setting up a delay period after the event is triggered.
- During this delay, if the event continues to fire, the function call is postponed.
- If the event doesn't fire again within the delay period, the function is finally executed.
- This helps ensure that the function is only called once after a series of rapid events
- preventing excessive function calls and improving performance.
//debounce.js
let counter = 0;
function debounce(func, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
function getData() {
console.log("Fetching data from API", counter++);
}
const handleGetData = debounce(getData, 300);<input type="text" onkeyup="handleGetData()">
<script src="./debounce.js"></script>