-
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.
- The debounce function takes two arguments: the
function to be debouncedand thedelayin milliseconds. - It returns a new function that wraps the original function call.
- When the wrapped function is triggered, it clears any existing timeout and sets a new one.
- If the wrapped function is triggered repeatedly within the specified delay, the previous timeout is canceled and a new one is set.
- This way, the original function is only executed after the delay period of no further events firing.
//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>- Input Fields - When user types in a search box, instead of firing searchEvent for every key stroke, we should debounce it and fire the searchEvent until the user pauses typing for a moment.
- Window Resize - Where we want to respond to window resize event, debouncing should be used to ensure that function is executed when the user has finished resizing the window. This prevents unnecessary function calls during rapid resizing.
- Scrolling Events for Animations - When we have animations trigerred by scroll events. Debouncing should be used to ensure animation starts when the user has paused scrolling. This prevents flickering caused by frequent starts, stops.
- Button Click - When we have a button and triggers an action. If we want to prevent accidental double clicks or rapid clicks. Debouncing will help to ensure function is executed once despite multiple clicks in quick succession.