---
title: "Timer · UI SDK — StyleX Blocks"
description: "Countdown and stopwatch with a large tabular readout and start, pause, resume and reset controls."
url: "https://stylexblocks.com/components/ui-sdk/timer/"
agent:
  instructions: "Use this search API to find relevant components and blocks across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://stylexblocks.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# Timer

Countdown and stopwatch with a large tabular readout and start, pause, resume and reset controls.

- Behavior engine: UI SDK
- Also available for: [Ark UI](https://stylexblocks.com/components/ark-ui/timer.md), [Base UI](https://stylexblocks.com/components/base-ui/timer.md)
- Category: Display
- Variants: plain, surface
- Sizes: sm, md, lg
- HTML page: https://stylexblocks.com/components/ui-sdk/timer/

## Install

Configure the project once (sets the behavior engine and import aliases):

```sh
npx stylexblocks init --style ui-sdk
```

Then add the item as source you own:

```sh
npx stylexblocks add timer
```

Equivalent: `npx shadcn add @stylexblocks/timer`. Registry item JSON: https://stylexblocks.com/r/ui-sdk/timer.json

## Usage

```tsx
import { Timer } from "#components/ui/ui-sdk/timer.tsx";
import { indigoPalette } from "@stylexblocks/ui/themes/palettes.ts";

export function Example() {
  return (
    // UI SDK has no timer primitive: Root runs a requestAnimationFrame
    // clock; Area is role="timer" and completion is announced once.
    // render / children functions receive the timer API as state
    <Timer.Root countdown startMs={5 * 60 * 1000} variant="plain" size="md" palette={indigoPalette}>
      <Timer.Area>
        <Timer.Item type="minutes" />
        <Timer.Separator>:</Timer.Separator>
        <Timer.Item type="seconds" />
      </Timer.Area>
      <Timer.Control>
        <Timer.ActionTrigger action="start">Start</Timer.ActionTrigger>
        <Timer.ActionTrigger action="pause">Pause</Timer.ActionTrigger>
        <Timer.ActionTrigger action="resume">Resume</Timer.ActionTrigger>
        <Timer.ActionTrigger action="reset">Reset</Timer.ActionTrigger>
      </Timer.Control>
    </Timer.Root>
  );
}

// stopwatch: <Timer.Root startMs={0}> (add targetMs to stop at a limit)
// completion: <Timer.Root onComplete={() => ...} completeLabel="Time's up">
```

## Source

`components/ui/ui-sdk/timer.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { createContext, useContext, useEffect, useMemo, useRef, useState } from "react";
import { mergeProps, renderElement, type PartProps } from "@ui-sdk/react/primitive";
import { createSlotRecipeContext } from "#lib/ui-sdk/create-slot-recipe-context.tsx";
import { defineSlotRecipe } from "#lib/recipe-props.ts";
import { colorPalette } from '@stylexblocks/ui/color-palette.stylex.ts'
import { durations } from '@stylexblocks/ui/tokens/durations.stylex.ts'
import { fontSizes } from '@stylexblocks/ui/tokens/font-sizes.stylex.ts'
import { fontWeights } from '@stylexblocks/ui/tokens/font-weights.stylex.ts'
import { letterSpacings } from '@stylexblocks/ui/tokens/letter-spacings.stylex.ts'
import { lineHeights } from '@stylexblocks/ui/tokens/line-heights.stylex.ts'
import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'
import { semanticRadii } from '@stylexblocks/ui/semantic-tokens/radii.stylex.ts'
import { semanticShadows } from '@stylexblocks/ui/semantic-tokens/shadows.stylex.ts'
import { sizes } from '@stylexblocks/ui/tokens/sizes.stylex.ts'
import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'

const timerRoot = stylex.create({
  base: {
    display: 'inline-flex',
    flexDirection: 'column',
    alignItems: 'center',
    gap: spacing._4,
    color: semanticColors.fg,
  },
})

const timerRootSizes = stylex.create({
  sm: {
    '--timer-font-size': fontSizes._2xl,
    '--timer-item-px': spacing._1_5,
    '--timer-item-py': spacing._1,
    '--timer-trigger-height': sizes.controlXs,
    '--timer-trigger-px': spacing._2,
    '--timer-trigger-font-size': fontSizes.xs,
  },
  md: {
    '--timer-font-size': fontSizes._4xl,
    '--timer-item-px': spacing._2,
    '--timer-item-py': spacing._1,
    '--timer-trigger-height': sizes.controlSm,
    '--timer-trigger-px': spacing._2_5,
    '--timer-trigger-font-size': fontSizes.sm,
  },
  lg: {
    '--timer-font-size': fontSizes._6xl,
    '--timer-item-px': spacing._3,
    '--timer-item-py': spacing._1_5,
    '--timer-trigger-height': sizes.controlMd,
    '--timer-trigger-px': spacing._3,
    '--timer-trigger-font-size': fontSizes.sm,
  },
})

/** The time readout: one big line of tabular numerals. */
const timerArea = stylex.create({
  base: {
    display: 'flex',
    alignItems: 'center',
    gap: spacing._1,
    fontSize: 'var(--timer-font-size)',
    lineHeight: 1,
    fontWeight: fontWeights.semibold,
    letterSpacing: letterSpacings.tight,
    fontVariantNumeric: 'tabular-nums',
  },
})

const timerItem = stylex.create({
  base: {
    minWidth: '2ch',
    textAlign: 'center',
    fontVariantNumeric: 'tabular-nums',
  },
})

const timerItemVariants = stylex.create({
  plain: {},
  surface: {
    paddingInline: 'var(--timer-item-px)',
    paddingBlock: 'var(--timer-item-py)',
    borderRadius: semanticRadii.panel,
    backgroundColor: colorPalette.subtle,
    color: colorPalette.fg,
    boxShadow: `inset 0 0 0 1px ${colorPalette.border}`,
  },
})

const timerSeparator = stylex.create({
  base: {
    color: semanticColors.fgSubtle,
    fontWeight: fontWeights.medium,
    userSelect: 'none',
  },
})

const timerControl = stylex.create({
  base: {
    display: 'flex',
    alignItems: 'center',
    gap: spacing._2,
  },
})

/** Start / pause / resume / reset buttons, styled like a `surface` Button. */
const timerActionTrigger = stylex.create({
  base: {
    display: {
      default: 'inline-flex',
      ':is([hidden])': 'none',
    },
    alignItems: 'center',
    justifyContent: 'center',
    gap: spacing._1_5,
    appearance: 'none',
    flexShrink: 0,
    userSelect: 'none',
    whiteSpace: 'nowrap',
    height: 'var(--timer-trigger-height)',
    minWidth: 'var(--timer-trigger-height)',
    paddingInline: 'var(--timer-trigger-px)',
    borderRadius: semanticRadii.control,
    fontFamily: 'inherit',
    fontSize: 'var(--timer-trigger-font-size)',
    lineHeight: lineHeights.sm,
    fontWeight: fontWeights.medium,
    color: colorPalette.fg,
    backgroundColor: {
      default: semanticColors.bg,
      ':hover': colorPalette.muted,
    },
    borderWidth: '1px',
    borderStyle: 'solid',
    borderColor: {
      default: `color-mix(in oklch, ${colorPalette.emphasized} 90%, transparent)`,
      ':hover': colorPalette.emphasized,
    },
    boxShadow: semanticShadows.xs,
    cursor: {
      default: 'pointer',
      ':is(:disabled, [disabled], [data-disabled])': 'not-allowed',
    },
    opacity: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 0.5,
    },
    transitionProperty: 'background-color, border-color, color, box-shadow',
    transitionDuration: durations.moderate,
    outlineWidth: {
      default: null,
      ':focus-visible': '1px',
    },
    outlineOffset: {
      default: null,
      ':focus-visible': '2px',
    },
    outlineStyle: {
      default: 'none',
      ':focus-visible': 'solid',
    },
    outlineColor: {
      default: null,
      ':focus-visible': colorPalette.focusRing,
    },
  },
})

export type TimerSize = keyof typeof timerRootSizes

export type TimerVariant = keyof typeof timerItemVariants

const timerRecipe = defineSlotRecipe({
  slots: {
    root: { styles: timerRoot, sizes: timerRootSizes },
    area: { styles: timerArea },
    item: { styles: timerItem, variants: timerItemVariants },
    separator: { styles: timerSeparator },
    control: { styles: timerControl },
    actionTrigger: { styles: timerActionTrigger },
  },
  defaultVariants: { size: "md", variant: "plain" },
});

const chrome = stylex.create({
  srOnly: {
    position: "absolute",
    width: "1px",
    height: "1px",
    padding: 0,
    margin: "-1px",
    overflow: "hidden",
    clip: "rect(0, 0, 0, 0)",
    whiteSpace: "nowrap",
    borderWidth: 0,
  },
});

export interface Time<T = number> {
  days: T;
  hours: T;
  minutes: T;
  seconds: T;
  milliseconds: T;
}

export type TimePart = keyof Time;
export type TimerAction = "start" | "pause" | "resume" | "reset" | "restart";

export interface TimerTickDetails {
  value: number;
  time: Time;
  formattedTime: Time<string>;
}

function msToTime(ms: number): Time {
  const t = Math.max(0, ms);
  return {
    days: Math.floor(t / 86_400_000),
    hours: Math.floor(t / 3_600_000) % 24,
    minutes: Math.floor(t / 60_000) % 60,
    seconds: Math.floor(t / 1000) % 60,
    milliseconds: t % 1000,
  };
}

const pad = (n: number, size = 2) => String(n).padStart(size, "0");

function formatTime(time: Time): Time<string> {
  return {
    days: pad(time.days),
    hours: pad(time.hours),
    minutes: pad(time.minutes),
    seconds: pad(time.seconds),
    milliseconds: pad(time.milliseconds, 3),
  };
}

export interface TimerApi {
  running: boolean;
  paused: boolean;
  /** Current value in milliseconds. */
  value: number;
  time: Time;
  formattedTime: Time<string>;
  /** 0–1 progress from `startMs` toward `targetMs`. */
  progressPercent: number;
  start: () => void;
  pause: () => void;
  resume: () => void;
  reset: () => void;
  restart: () => void;
}

const TimerContext = createContext<TimerApi | null>(null);

function useTimer() {
  const ctx = useContext(TimerContext);
  if (!ctx) throw new Error("Timer parts must be rendered inside <Timer.Root>");
  return ctx;
}

export type TimerRootOwnProps = {
  /** Count down from `startMs` to `targetMs` (default 0) instead of up. */
  countdown?: boolean;
  /** Starting value in milliseconds. */
  startMs?: number;
  /** Value at which the timer completes (required for a stopwatch to stop). */
  targetMs?: number;
  /** Start running on mount. */
  autoStart?: boolean;
  /** Tick granularity in milliseconds. */
  interval?: number;
  onTick?: (details: TimerTickDetails) => void;
  onComplete?: () => void;
  /** Announced to screen readers when the timer reaches its target. */
  completeLabel?: string;
};

type Status = "idle" | "running" | "paused";

function RootNode({
  render,
  countdown = false,
  startMs = 0,
  targetMs,
  autoStart = false,
  interval = 1000,
  onTick,
  onComplete,
  completeLabel = "Timer complete",
  children,
  ...rest
}: PartProps<"div", TimerApi> & TimerRootOwnProps) {
  const [status, setStatus] = useState<Status>(autoStart ? "running" : "idle");
  const [currentMs, setCurrentMs] = useState(startMs);
  const [announcement, setAnnouncement] = useState("");
  // bumped by reset/restart so a running clock re-anchors its origin
  const [epoch, setEpoch] = useState(0);
  const target = targetMs ?? (countdown ? 0 : undefined);

  const valueRef = useRef(currentMs);
  valueRef.current = currentMs;
  const callbacks = useRef({ onTick, onComplete, completeLabel });
  callbacks.current = { onTick, onComplete, completeLabel };

  // requestAnimationFrame clock: whole intervals are accounted against a
  // fixed origin, so a throttled background tab catches up on return.
  useEffect(() => {
    if (status !== "running") return;
    let origin = performance.now();
    let frame = requestAnimationFrame(function loop(now) {
      const steps = Math.floor((now - origin) / interval);
      if (steps > 0) {
        origin += steps * interval;
        const sign = countdown ? -1 : 1;
        let next = valueRef.current + sign * steps * interval;
        if (target != null) next = countdown ? Math.max(next, target) : Math.min(next, target);
        valueRef.current = next;
        setCurrentMs(next);
        const time = msToTime(next);
        callbacks.current.onTick?.({ value: next, time, formattedTime: formatTime(time) });
        if (target != null && (countdown ? next <= target : next >= target)) {
          setStatus("idle");
          setAnnouncement(callbacks.current.completeLabel);
          callbacks.current.onComplete?.();
          return;
        }
      }
      frame = requestAnimationFrame(loop);
    });
    return () => cancelAnimationFrame(frame);
  }, [status, epoch, interval, countdown, target]);

  const api = useMemo<TimerApi>(() => {
    const time = msToTime(currentMs);
    const range = (target ?? 0) - startMs;
    const progress = range === 0 ? 0 : (currentMs - startMs) / range;
    const run = () => {
      setAnnouncement("");
      setStatus("running");
    };
    return {
      running: status === "running",
      paused: status === "paused",
      value: currentMs,
      time,
      formattedTime: formatTime(time),
      progressPercent: Math.min(Math.max(progress, 0), 1),
      start: () => {
        if (status === "idle") run();
      },
      pause: () => {
        if (status === "running") setStatus("paused");
      },
      resume: () => {
        if (status === "paused") run();
      },
      reset: () => {
        valueRef.current = startMs;
        setCurrentMs(startMs);
        setEpoch((e) => e + 1);
        if (status === "paused") setStatus("idle");
      },
      restart: () => {
        valueRef.current = startMs;
        setCurrentMs(startMs);
        setEpoch((e) => e + 1);
        run();
      },
    };
  }, [status, currentMs, startMs, target]);

  const element = renderElement(
    "div",
    mergeProps(
      {
        "data-state": status,
        children: (
          <>
            {typeof children === "function" ? children(api) : children}
            <span role="status" aria-live="polite" {...stylex.props(chrome.srOnly)}>
              {announcement}
            </span>
          </>
        ),
      },
      rest,
    ),
    render,
    api,
  );
  return <TimerContext.Provider value={api}>{element}</TimerContext.Provider>;
}

function AreaNode({ render, ...rest }: PartProps<"div", TimerApi>) {
  const api = useTimer();
  const { days, hours, minutes, seconds } = api.formattedTime;
  return renderElement(
    "div",
    mergeProps(
      {
        // role="timer" is implicitly aria-live="off": no per-tick chatter
        role: "timer",
        "aria-atomic": true,
        "aria-label": `${Number(days)} days ${hours}:${minutes}:${seconds}`,
      },
      rest,
    ),
    render,
    api,
  );
}

function ItemNode({
  render,
  type,
  ...rest
}: PartProps<"div", TimerApi> & { type: TimePart }) {
  const api = useTimer();
  return renderElement(
    "div",
    mergeProps(
      {
        "data-type": type,
        style: { "--value": api.time[type] } as React.CSSProperties,
        children: api.formattedTime[type],
      },
      rest,
    ),
    render,
    api,
  );
}

function SeparatorNode({ render, ...rest }: PartProps<"div">) {
  return renderElement("div", mergeProps({ "aria-hidden": true }, rest), render);
}

function ActionTriggerNode({
  render,
  action,
  ...rest
}: PartProps<"button", TimerApi> & { action: TimerAction }) {
  const api = useTimer();
  const idle = !api.running && !api.paused;
  const hidden = {
    start: !idle,
    pause: !api.running,
    resume: !api.paused,
    reset: idle,
    restart: false,
  }[action];
  return renderElement(
    "button",
    mergeProps(
      {
        type: "button" as const,
        hidden,
        "data-action": action,
        onClick: (event: React.MouseEvent) => {
          if (!event.defaultPrevented) api[action]();
        },
      },
      rest,
    ),
    render,
    api,
  );
}

/** Render-prop access to the timer API, like Ark's `Timer.Context`. */
function TimerContextConsumer({ children }: { children: (api: TimerApi) => React.ReactNode }) {
  return <>{children(useTimer())}</>;
}

const { withProvider, withContext } = createSlotRecipeContext(timerRecipe);

/**
 * Timer — a countdown or stopwatch. UI SDK ships no timer primitive, so
 * Root runs the clock itself (requestAnimationFrame, whole `interval`
 * ticks) with start / pause / resume / reset / restart, counting down from
 * `startMs` with `countdown` or up toward an optional `targetMs`.
 * `<Timer.Root variant size>` resolves the recipe once; every part inherits
 * it through context. Area is `role="timer"` (silent while running); a
 * polite live region announces completion once. ActionTriggers hide when
 * their action doesn't apply. Composition per part via `render`, whose
 * function form (and Root's `children` function) receives the timer API.
 */
export const Timer = {
  Root: withProvider(RootNode, "root", "TimerRoot"),
  Area: withContext(AreaNode, "area", "TimerArea"),
  Item: withContext(ItemNode, "item", "TimerItem"),
  Separator: withContext(SeparatorNode, "separator", "TimerSeparator"),
  Control: withContext("div", "control", "TimerControl"),
  ActionTrigger: withContext(ActionTriggerNode, "actionTrigger", "TimerActionTrigger"),
  Context: TimerContextConsumer,
};

export type TimerRootProps = React.ComponentProps<typeof Timer.Root>;
export type TimerItemProps = React.ComponentProps<typeof Timer.Item>;
export type TimerActionTriggerProps = React.ComponentProps<typeof Timer.ActionTrigger>;
```
