> For the complete documentation index, see [llms.txt](https://jscula.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jscula.gitbook.io/docs/utils/debounce.md).

# debounce

`debounce()` waits until an event stops happening before running a function.

It is useful for events that can fire many times quickly, such as typing, resizing, or scrolling.

### `debounce(listener, delay)`

```javascript
const delayedListener = debounce(listener, delay);
```

Each new event restarts the timer. The listener runs only after no new event occurs for `delay` milliseconds.

For example, with a `300` millisecond delay:

1. A user types a character.
2. The 300 ms timer starts.
3. The user types again before it ends.
4. The timer restarts.
5. The listener runs 300 ms after the final keystroke.

### Parameters

* `listener`: The function to run after the event pauses.
* `delay`: The wait time in milliseconds.

### Use cases

Use `debounce()` to:

* Search after a user stops typing.
* Save a draft after input pauses.
* Recalculate layout after window resizing ends.

### Examples

Search after the user pauses typing:

```javascript
$('#search').on('input', debounce(function() {
  search(this.val());
}, 300));
```

Save a draft after the user stops editing:

```javascript
$('#message').on('input', debounce(function() {
  saveDraft(this.val());
}, 1000));
```

Run layout work once after resizing ends:

```javascript
window.addEventListener('resize', debounce(() => {
  updateLayout();
}, 200));
```

{% hint style="info" %}
Choose a short delay for search, often 200–400 ms. Use a longer delay for draft saving.
{% endhint %}
