# useInterval

Calls `callback` every `delayMs` milliseconds. Pass `null` as the delay to pause. Always calls the latest `callback`, so it can read current state without restarting the timer.

The timer restarts only when `delayMs` changes or it is paused and resumed. Browsers slow timers in background tabs (to once a second or less), so don't count ticks to measure time; compare `Date.now()` or use `useNow`. Cleared on unmount. Nothing runs on the server.

## Import

```ts
import { useInterval } from '@vincent.ri/react-tils'
// or only this hook
import { useInterval } from '@vincent.ri/react-tils/useInterval'
```

## Usage

```ts
const [count, setCount] = useState(0)
useInterval(() => setCount(count + 1), running ? 1000 : null)

// Poll every 5s, but not while the tab is in the background.
useInterval(refresh, 5000, { pauseWhenHidden: true })
```

## When to use it

Polling an API, a countdown or clock, or rotating a carousel.

## When not to

You need a single delay; use `setTimeout` in an event handler or effect. For animation, use CSS or `requestAnimationFrame`. Server data that changes often may suit a data-fetching library with built-in refetching.

## API

```ts
function useInterval(callback: () => void, delayMs: number | null, options?: IntervalOptions): void
```

| Parameter | Description |
| --- | --- |
| `callback` | Called on every tick. Can change every render. |
| `delayMs` | Milliseconds between ticks, or `null` to pause. |
| `options` | `pauseWhenHidden`. Optional. |

### Types

```ts
export type IntervalOptions = {
  /** Pause while the tab is hidden, and resume when it is visible again. Default `false`. */
  pauseWhenHidden?: boolean;
};
```

## Browser support

Works in all modern browsers.

---

243 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useInterval.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useInterval/
Previous: [useCaretPosition](https://vincentri.github.io/react-tils/hooks/useCaretPosition.md)
Next: [useTimeout](https://vincentri.github.io/react-tils/hooks/useTimeout.md)
