Debounce Method
The debounce
function is used to limit the rate at which a specified function is executed. This helps in managing performance and avoiding unnecessary function calls during rapid or frequent events such as resizing, scrolling, or typing in an input field. It postpones the execution of the function until after a specified wait time has elapsed since the last invocation, or immediately at the beginning if specified.
Parameters
- func (
Function
): The function to debounce. It is the primary action you want to throttle. - wait (
Number
=300
): Optional. The number of milliseconds to delay before invokingfunc
after it was last called. Defaults to 300ms. - immediate (
Boolean
=false
): Optional. Iftrue
, triggers the function on the leading edge instead of the trailing edge of the wait interval. Defaults tofalse
.
Return Value
Returns a debounced version of the original function func
. This new function will delay the execution of func
according to the wait
time after the last call, or execute immediately if immediate
is set to true
.
Example Usage
<div class="w-screen h-screen grid place-items-center">
<input class="border rounded-md p-1" id="searchInput" type="text" placeholder="Search">
</div>
<script>
// Example: Debouncing a search input function
const debounceSearch = debounce(() => {
console.log('Search query submitted');
}, 1000);
// Attach the debounced function to an input event listener
document.getElementById('searchInput').addEventListener('input', debounceSearch);
</script>
Implementation Notes
When implementing the debounce
function, it's important to consider the nature of the event and its frequency. Selecting an appropriate wait
time is crucial for optimizing performance without negatively impacting user experience. For immediate actions, setting immediate
to true
can provide a responsive experience where necessary.