> For the complete documentation index, see [llms.txt](https://choubey.gitbook.io/javascript-interview-questions/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://choubey.gitbook.io/javascript-interview-questions/question-66.md).

# 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:

```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:**

1. **`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.
2. **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 `timeoutId` and `func`.
   * It also takes any arguments (`...args`) passed to it when the original event is triggered.
3. **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.
4. **Setting New Timeout:**
   * `timeoutId = setTimeout(() => { func.apply(this, args); }, delay);`: A new timeout is set using `setTimeout`. The function to be executed (`func`) is called after the specified `delay`, and it's passed the captured arguments (`args`).
5. **Example Usage:**
   * We call `debounce` to create a debounced version of `handleResize`.
   * This debounced version is then attached as an event listener to the 'resize' event on the window.
