# Timer
Package: @mantine/core
Import: import { Timer } from '@mantine/core';
Description: Controllable countdown and stopwatch timer

## Usage

`Timer` is a stopwatch and countdown that can be started, paused, resumed, reset and restarted.
It does not render playback buttons: add them with [Timer.Control](#custom-layout) or control
the timer with [useTimer](#controlling-the-timer). Set `autoStart` to start the timer on mount:

```tsx
import { Timer } from '@mantine/core';

function Demo() {
  return <Timer countdown startMs={90 * 1000} autoStart />;
}
```


## Countdown and stopwatch

By default, `Timer` counts up from `startMs`. Set `countdown` prop to count down
from `startMs` to `targetMs` instead. In both modes the timer stops at `targetMs` and calls `onComplete`:

```tsx
import { Timer } from '@mantine/core';

function Demo() {
  return (
    <>
      {/* Stopwatch: counts up from 0 */}
      <Timer autoStart />

      {/* Countdown: counts down from 90 seconds to 0 */}
      <Timer countdown startMs={90 * 1000} autoStart />
    </>
  );
}
```

Changing `startMs` or `countdown` stops the timer and resets it to the new `startMs`.

## Format

Set `format` prop to change the readout, `'HH:mm:ss'` by default:

Literal text is not escaped: token letters are replaced with time values even inside words.
All tokens except days are capped to their natural range, include a larger token
for durations that exceed the largest unit in the format:

```tsx
import { Stack, Timer } from '@mantine/core';

function Demo() {
  return (
    <Stack align="center">
      <Timer countdown startMs={41_115_000} format="HH:mm:ss" autoStart />
      <Timer countdown startMs={330_000} format="mm:ss" autoStart />
      <Timer countdown startMs={194_400_000} format="DD:HH:mm:ss" autoStart />
    </Stack>
  );
}
```


To display milliseconds, lower the `interval` prop so the readout updates more often than once per second:

```tsx
import { Timer } from '@mantine/core';

function Demo() {
  return <Timer format="mm:ss:SS" interval={10} autoStart />;
}
```


## Custom layout

Pass `Timer.Segment`, `Timer.Separator` and `Timer.Control` as children to replace
the default readout. `Timer.Control` is a button that calls the controller action
set with the `action` prop:

```tsx
import { ActionIcon, Group, Timer } from '@mantine/core';
import { ArrowCounterClockwiseIcon, PauseIcon, PlayIcon } from '@phosphor-icons/react';

function Demo() {
  return (
    <Timer countdown startMs={5 * 60 * 1000} autoStart>
      <Group gap={4} fz={36} fw={700}>
        <Timer.Segment type="minutes" />
        <Timer.Separator>:</Timer.Separator>
        <Timer.Segment type="seconds" />
      </Group>

      <Group gap="xs">
        <Timer.Control action="start" aria-label="Start">
          <ActionIcon component="span" variant="light">
            <PlayIcon size={18} weight="fill" />
          </ActionIcon>
        </Timer.Control>
        <Timer.Control action="pause" aria-label="Pause">
          <ActionIcon component="span" variant="light">
            <PauseIcon size={18} weight="fill" />
          </ActionIcon>
        </Timer.Control>
        <Timer.Control action="restart" aria-label="Restart">
          <ActionIcon component="span" variant="light">
            <ArrowCounterClockwiseIcon size={18} />
          </ActionIcon>
        </Timer.Control>
      </Group>
    </Timer>
  );
}
```


## useTimer hook

`Timer` supports the [controller pattern](https://alpha.mantine.dev/llms/guides-controllers.md) with the `useTimer` hook.
It accepts the same options as `Timer` props and returns the timer state and actions:

```tsx
import { useTimer } from '@mantine/core';

function Demo() {
  const controller = useTimer({ countdown: true, startMs: 60 * 1000 });

  controller.getValue(); // -> { totalMs, days, hours, minutes, seconds, milliseconds }
  controller.isRunning(); // -> boolean, true while the timer is counting
  controller.isPaused(); // -> boolean, true when the timer is started and then paused
  controller.getProgress(); // -> number from 0 to 1 when the boundary is set

  controller.start(); // starts from the current value, or from startMs after the timer has completed
  controller.pause();
  controller.resume();
  controller.reset(); // stops and resets the value to startMs
  controller.restart(); // resets and starts again

  return null;
}
```

## Controlling the timer

Pass the controller created with `useTimer` to the `controller` prop.
Timer options set on `Timer` are then ignored, pass them to `useTimer` instead:

```tsx
import { Button, Group, Stack, Text, Timer, useTimer } from '@mantine/core';

function Demo() {
  const controller = useTimer({ countdown: true, startMs: 60 * 1000, interval: 100 });

  return (
    <Stack align="center">
      <Timer controller={controller} format="mm:ss:SS" fz={40} fw={700} />

      <Text c="dimmed" size="sm">
        running: {String(controller.isRunning())}, paused: {String(controller.isPaused())}
      </Text>

      <Group>
        <Button onClick={controller.start} disabled={controller.isRunning()}>Start</Button>
        <Button onClick={controller.pause} disabled={!controller.isRunning()} variant="default">Pause</Button>
        <Button onClick={controller.resume} disabled={controller.isRunning()} variant="default">Resume</Button>
        <Button onClick={controller.reset} variant="default">Reset</Button>
        <Button onClick={controller.restart} variant="default">Restart</Button>
      </Group>
    </Stack>
  );
}
```


## Progress

When `targetMs` is set, `getProgress()` returns a value from `0` to `1`.
Use it with [Progress](https://alpha.mantine.dev/llms/core-progress.md) or `RingProgress`:

```tsx
import { Progress, Stack, Timer, useTimer } from '@mantine/core';

function Demo() {
  const controller = useTimer({ countdown: true, startMs: 30 * 1000, autoStart: true, interval: 50 });

  return (
    <Stack>
      <Timer controller={controller} format="ss:SSS" fz={32} fw={700} style={{ alignSelf: 'center' }} />
      <Progress value={controller.getProgress() * 100} transitionDuration={50} />
    </Stack>
  );
}
```


## Timer.parse

`Timer.parse` (also available as `useTimer.parse`) converts a duration object, `Date` or ISO date
string to milliseconds:

```tsx
import { Timer } from '@mantine/core';

Timer.parse(90 * 1000); // -> 90000
Timer.parse({ minutes: 25 }); // -> 1500000
Timer.parse({ hours: 1, minutes: 30 }); // -> 5400000
Timer.parse('2030-01-01T00:00:00'); // -> milliseconds from now until the date
```

With a `Date` or a date string, the result depends on the current time. Calculate it once,
for example, in a `useState` initializer: a new `startMs` value on every render resets the timer:

```tsx
import { useState } from 'react';
import { Timer } from '@mantine/core';

function Demo() {
  const [remaining] = useState(() => Timer.parse('2030-01-01T00:00:00'));
  return <Timer countdown startMs={remaining} format="DD:HH:mm:ss" autoStart />;
}
```


## Timer vs use-countdown

[use-countdown](https://alpha.mantine.dev/llms/hooks-use-countdown.md) is a display-only countdown hook. Use `Timer` or `useTimer`
when the timer must count up or be paused, resumed and restarted.

## Accessibility

Set `aria-label` on icon-only timer controls. If ticks need to be announced, use `aria-live="polite"`
with an interval of at least one second:

```tsx
import { Timer } from '@mantine/core';

function Demo() {
  return (
    <Timer countdown startMs={60 * 1000} interval={1000} aria-live="polite">
      <Timer.Segment type="minutes" />
      <Timer.Separator />
      <Timer.Segment type="seconds" />
      <Timer.Control action="start" aria-label="Start timer">
        ▶
      </Timer.Control>
    </Timer>
  );
}
```


#### Props

**Timer props**

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| autoStart | boolean | - | If set, the timer starts automatically on mount, `false` by default |
| children | React.ReactNode | - | Custom layout built with `Timer.Segment`, `Timer.Separator` and `Timer.Control` compound components |
| controller | TimerController | - | Controller returned by the `useTimer` hook. When provided, the timer is controlled externally and the option props below are ignored |
| countdown | boolean | - | If set, the timer counts down instead of up, `false` by default |
| format | string | - | Format of the default readout, `'HH:mm:ss'` by default. Supported tokens: `DD`/`D` – days, `HH`/`H` – hours, `mm`/`m` – minutes, `ss`/`s` – seconds (two-letter tokens are zero-padded), `SSS` – milliseconds padded to 3 digits, `SS` – hundredths of a second, `S` – milliseconds unpadded. Literal text is not escaped: the letters `D`, `H`, `m`, `s` and `S` are always replaced |
| interval | number | - | Tick interval in milliseconds, `1000` by default, values below `1` are clamped to `1` |
| onComplete | () => void | - | Called once when the timer reaches its target boundary |
| onTick | (value: TimerValue) => void | - | Called on every tick with the current timer value |
| startMs | number | - | Initial elapsed (stopwatch) or remaining (countdown) time in milliseconds, `0` by default. Changing `startMs` or `countdown` stops the timer and resets it to the new `startMs` |
| targetMs | number | - | Boundary the timer counts up to (stopwatch) or down to (countdown). Defaults to `0` in countdown mode, open-ended in stopwatch mode. If `startMs` is already at or past the boundary, the timer completes immediately when started |

**Timer.Segment props**

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| pad | number | - | Number of digits the value is padded with leading zeros to, `2` by default (`3` for milliseconds) |
| type | "days" \| "hours" \| "minutes" \| "seconds" \| "milliseconds" | required | Time segment to display |

**Timer.Separator props**

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| children | React.ReactNode | - | Separator content, `:` by default |

**Timer.Control props**

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| action | TimerControlAction | required | Controller action called when the control is clicked |


#### Styles API

Timer component supports Styles API. With Styles API, you can customize styles of any inner element. Follow the documentation to learn how to use CSS modules, CSS variables and inline styles to get full control over component styles.

**Timer selectors**

| Selector | Static selector | Description |
|----------|----------------|-------------|
| root | .mantine-Timer-root | Root element |
| value | .mantine-Timer-value | Default readout element, rendered when Timer has no children |
| segment | .mantine-Timer-segment | Timer.Segment element, displays a single time segment |
| separator | .mantine-Timer-separator | Timer.Separator element, displays a separator between segments |
| control | .mantine-Timer-control | Timer.Control element, a button that calls a controller action |

**Timer data attributes**

| Selector | Attribute | Condition | Value |
|----------|-----------|-----------|-------|
| segment | data-segment | - | Type of the segment (days, hours, minutes, seconds, milliseconds) |
| control | data-action | - | Controller action of the control (start, pause, resume, reset, restart) |
