Question 66
Question
How would you implement a custom debounce function for handling event throttling?
Answer
Debouncing is essential for optimizing performance in applications where events fire frequently, like scrolling or resizing. Here's how you can implement a custom debounce function in JavaScript:
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId); // Clear any previous timeout
timeoutId = setTimeout(() => {
func.apply(this, args); // Call the original function after the delay
}, delay);
};
}
// Example usage:
const handleResize = () => {
console.log('Window resized!');
// Perform actions when window is resized
};
const debouncedResizeHandler = debounce(handleResize, 300); // Debounce with a delay of 300ms
window.addEventListener('resize', debouncedResizeHandler);Explanation:
debounce(func, delay)Function:Takes two arguments:
func: The function you want to debounce (in this case,handleResize).delay: The time in milliseconds to wait before executing the function.
Inner Closure (
return function(...args)):Returns a new function that will be called whenever the original event happens (e.g., window resize).
This inner function captures the variables
timeoutIdandfunc.It also takes any arguments (
...args) passed to it when the original event is triggered.
Clearing Timeout:
clearTimeout(timeoutId);: Inside the closure, before setting a new timeout, we clear any existing timeout. This ensures that only the latest call will trigger the function after the delay.
Setting New Timeout:
timeoutId = setTimeout(() => { func.apply(this, args); }, delay);: A new timeout is set usingsetTimeout. The function to be executed (func) is called after the specifieddelay, and it's passed the captured arguments (args).
Example Usage:
We call
debounceto create a debounced version ofhandleResize.This debounced version is then attached as an event listener to the 'resize' event on the window.
Last updated