# Debouncing

Debouncing is a programming practice used to ensure that time-consuming tasks do not fire so often that they stall the performance of the web page. In other words, it limits the rate at which a function can fire.

## 1. The Concept

Imagine an elevator. The elevator doesn't leave immediately when the first person enters. It waits for a few seconds. If another person enters, the timer resets. The elevator only leaves when no new person has entered for the specified duration.

In JavaScript, debouncing forces a function to wait a certain amount of time before running. If the event is triggered again within that time, the timer resets.

## 2. Implementation

A basic debounce function takes a function (`func`) and a delay (`wait`) as arguments.

```javascript
function debounce(func, wait) {
  let timeout;

  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func.apply(this, args);
    };

    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}
```

## 3. Practical Use Case: Search Input

Without debouncing, an API call would be made for every keystroke.
*   User types "Apple".
*   Events: "A", "Ap", "App", "Appl", "Apple".
*   5 API calls.

With debouncing (e.g., 300ms), the API call is only made once the user stops typing for 300ms.

```javascript
const searchInput = document.getElementById('search');

function performSearch(query) {
  console.log('Searching for:', query);
  // API call logic here
}

const debouncedSearch = debounce((event) => {
  performSearch(event.target.value);
}, 300);

searchInput.addEventListener('input', debouncedSearch);
```

## 4. Debouncing vs. Throttling

*   **Debounce:** "Group multiple calls into one single call." (Execute only after a period of inactivity).
    *   *Use case:* Search bar, resizing window (wait until done).
*   **Throttle:** "Execute at most once every X milliseconds." (Execute at a steady rate).
    *   *Use case:* Scrolling, mouse movement, gaming inputs.

[[programming/javascript/vanilla/javascript]]
[[programming/throttling-pattern]]
[[programming/javascript/vanilla/events]]