# debounce

> Wrap a callback so it fires only once a quiet period (`waitMs`) elapses after the last call. Returns a function with a `.cancel()` method for safe teardown.

Source: https://ngwr.dev/reference/utils/debounce  
Kind: Util

## Usage

```angular-ts
import { debounce } from 'ngwr/utils';

const onResize = debounce(() => recalcLayout(), 150);
window.addEventListener('resize', onResize);

// Cancel any pending invocation on teardown:
onResize.cancel();
```

## Why ngwr provides this

Resize / input / scroll handlers almost always want debouncing. Rolling your own with `setTimeout` / `clearTimeout` is doable but easy to leak on teardown, and reaching for lodash pulls ~70 KB just for one helper. ngwr's version is tiny and exposes `.cancel()` so the host's `DestroyRef.onDestroy` can clean up cleanly.

```angular-ts
// Native — manual timer dance, easy to leak on teardown.
let t: ReturnType<typeof setTimeout> | undefined;
function onResize() {
  if (t) clearTimeout(t);
  t = setTimeout(() => recalcLayout(), 150);
}
// → on destroy, you need to remember to `clearTimeout(t)` yourself.

// lodash — ~70 KB pulled in just for one utility.

// ngwr — tiny, with `.cancel()` for safe teardown.
const onResize = debounce(() => recalcLayout(), 150);
destroyRef.onDestroy(() => onResize.cancel());
```

## API

| Name | Description | Type | Default |
| --- | --- | --- | --- |
| `debounce(fn, waitMs)` | Returns a wrapper that fires `fn` only once `waitMs` has elapsed without further calls. The wrapper exposes a `.cancel()` method for cleanup. | `(fn, ms) => WrDebouncedFn` | `—` |
