Skip to content
Atoms

Countdown

Time left, with digits that roll.

Installation

  1. Run the CLI

    Run pnpm dlx asta-ui@latest init once, then this. The file lands in components/astabyte/ and the colour tokens go into your CSS.

    $ pnpm dlx asta-ui@latest add countdown

    Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/countdown.json

  2. Or install the package

    Don’t want the file? Import from asta-ui/countdown and update with pnpm update asta-ui. Add the stylesheet once. More.

    $ pnpm add asta-ui
    import { Countdown } from "asta-ui/countdown";
  3. Or copy it by hand

    Copy this file. Keep the paths, or fix the @/ imports. Then add the tokens from globals.css.

    "use client";
    
    import { useEffect, useRef, useState } from "react";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    
    const KEYFRAMES = `@keyframes asta-cd-in { from { transform: translateY(-62%); opacity: 0 } }
    @keyframes asta-cd-out { to { transform: translateY(62%); opacity: 0 } }
    @media (prefers-reduced-motion: reduce) { .asta-cd-a { animation: none !important } .asta-cd-old { display: none } }`;
    
    export type CountdownUnit = "d" | "h" | "m" | "s";
    
    const UNIT_MS: Record<CountdownUnit, number> = { d: 86_400_000, h: 3_600_000, m: 60_000, s: 1000 };
    const NAMES: Record<CountdownUnit, [string, string]> = { d: ["day", "days"], h: ["hour", "hours"], m: ["minute", "minutes"], s: ["second", "seconds"] };
    const SHORT: Record<CountdownUnit, string> = { d: "Days", h: "Hours", m: "Min", s: "Sec" };
    
    export interface CountdownProps {
      /** The moment it counts down to: a Date, a timestamp in ms, or an ISO string. */
      to: Date | number | string;
      /** Which units to show, biggest first. The biggest one soaks up the rest, e.g. ["h","m","s"] shows 49 hours. */
      units?: CountdownUnit[];
      /** `boxed` puts each unit on a tile with a label under it. `inline` reads like a clock, 04:59. */
      variant?: "boxed" | "inline";
      size?: "sm" | "md" | "lg";
      /** Called once when it reaches zero. */
      onComplete?: () => void;
      /** Accessible name in front of the time, e.g. "Sale ends in". */
      label?: string;
      className?: string;
    }
    
    const toMs = (t: CountdownProps["to"]) => (t instanceof Date ? t.getTime() : typeof t === "string" ? Date.parse(t) : t);
    
    /** Splits what's left into the units shown. The first unit takes everything above it. */
    function split(left: number, units: CountdownUnit[]) {
      let rest = Math.max(0, left);
      return units.map((u) => {
        const n = Math.floor(rest / UNIT_MS[u]);
        rest -= n * UNIT_MS[u];
        return n;
      });
    }
    
    /** One digit. The old one drops out below while the new one drops in from above. */
    function Digit({ d }: { d: string }) {
      const [state, setState] = useState({ cur: d, prev: "", n: 0 });
      if (state.cur !== d) setState({ cur: d, prev: state.cur, n: state.n + 1 });
      return (
        <span className="relative inline-block h-[1em] w-[0.62em] overflow-hidden text-center leading-[1em]">
          {state.n > 0 && (
            <span key={`o${state.n}`} className="asta-cd-a asta-cd-old absolute inset-0 animate-[asta-cd-out_.5s_cubic-bezier(.16,1,.3,1)_both]">
              {state.prev}
            </span>
          )}
          <span key={`n${state.n}`} className={cx("asta-cd-a block", state.n > 0 && "animate-[asta-cd-in_.5s_cubic-bezier(.16,1,.3,1)_both]")}>
            {state.cur}
          </span>
        </span>
      );
    }
    
    const SIZE = {
      sm: { num: "text-[15px]", tile: "min-w-[38px] rounded-md px-1.5 py-1.5", label: "text-[9.5px]", gap: "gap-1.5" },
      md: { num: "text-[24px]", tile: "min-w-[56px] rounded-[10px] px-2 py-2.5", label: "text-[10.5px]", gap: "gap-2" },
      lg: { num: "text-[40px]", tile: "min-w-[80px] rounded-xl px-3 py-3.5", label: "text-[11px]", gap: "gap-2.5" },
    };
    
    /**
     * Time left until a moment, in days, hours, minutes and seconds. Each digit rolls down to the next one as it
     * changes. It ticks once a second, and stops while it is offscreen or the tab is hidden.
     */
    export function Countdown({ to, units = ["d", "h", "m", "s"], variant = "boxed", size = "md", onComplete, label = "Time left", className }: CountdownProps) {
      const target = toMs(to);
      const root = useRef<HTMLSpanElement>(null);
      const [now, setNow] = useState<number | null>(null);
      const done = useRef(false);
      const complete = useRef(onComplete);
      useEffect(() => {
        complete.current = onComplete;
      });
    
      useEffect(() => {
        const el = root.current;
        if (!el) return;
        done.current = false;
        let id = 0;
        let visible = true;
        const stop = () => {
          window.clearInterval(id);
          id = 0;
        };
        const tick = () => {
          const t = Date.now();
          setNow(t);
          if (t >= target) {
            stop();
            if (!done.current) {
              done.current = true;
              complete.current?.();
            }
          }
        };
        const sync = () => {
          const run = visible && !document.hidden && Date.now() < target;
          if (run && !id) {
            tick();
            id = window.setInterval(tick, 1000);
          } else if (!run) {
            stop();
            if (Date.now() >= target) tick();
          }
        };
        const io = new IntersectionObserver(([e]) => {
          visible = e.isIntersecting;
          sync();
        });
        io.observe(el);
        document.addEventListener("visibilitychange", sync);
        sync();
        return () => {
          stop();
          io.disconnect();
          document.removeEventListener("visibilitychange", sync);
        };
      }, [target]);
    
      const parts = now === null ? units.map(() => 0) : split(target - now, units);
      const ready = now !== null;
      const spoken = units
        .map((u, i) => (i < units.length - 1 || u !== "s" ? `${parts[i]} ${NAMES[u][parts[i] === 1 ? 0 : 1]}` : ""))
        .filter(Boolean)
        .join(" ");
      const s = SIZE[size];
    
      return (
        <span
          ref={root}
          role="timer"
          aria-label={ready ? `${label}: ${spoken}` : label}
          className={cx("inline-flex items-start font-medium tabular-nums tracking-[-0.03em] text-ink transition-opacity duration-500", variant === "boxed" && s.gap, !ready && "opacity-0", className)}
        >
          <style href="asta-countdown" precedence="asta">{KEYFRAMES}</style>
          {units.map((u, i) => {
            const text = String(parts[i]).padStart(2, "0");
            const digits = (
              <span aria-hidden className={cx("inline-flex leading-none", s.num)}>
                {text.split("").map((d, k) => (
                  <Digit key={text.length - k} d={d} />
                ))}
              </span>
            );
            if (variant === "inline")
              return (
                <span key={u} className="inline-flex items-start">
                  {i > 0 && (
                    <span aria-hidden className={cx("-mt-[0.06em] px-[0.08em] leading-none text-mute", s.num)}>
                      :
                    </span>
                  )}
                  {digits}
                </span>
              );
            return (
              <span key={u} className="flex flex-col items-center gap-1.5">
                <span className={cx("flex justify-center bg-paper-2 shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_8%,transparent)]", s.tile)}>{digits}</span>
                <span aria-hidden className={cx("font-mono uppercase tracking-wider text-mute", s.label)}>
                  {SHORT[u]}
                </span>
              </span>
            );
          })}
        </span>
      );
    }
    
    export default Countdown;
    
  4. Or ask your AI agent

    Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.

    Add the Astabyte UI Countdown component to my project.
    
    Time left, with digits that roll.
    It includes: boxed, inline, units, sm, md, lg, onComplete, timer role.
    
    Install it:
    ```sh
    pnpm dlx asta-ui@latest add countdown --radix
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/countdown.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { Button } from "@/components/astabyte/button";
    import { Countdown } from "@/components/astabyte/countdown";
    ```
    
    Usage example and props: https://ui.astabyte.com/countdown
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
  5. Or use plain HTML + CSS

    Not on React? Use it from Django, Rails, Laravel, Go html/template, htmx or a static page. Load asta.css and asta.js once (the head.html tab), then paste the markup. The ui.astabyte.com/cdn link is temporary: pin a version from jsDelivr for production. More in HTML + CSS.

    <!-- asta.js ticks every countdown once a second and pauses it off screen. Set data-asta-countdown to an ISO date. -->
    <div style="display:flex;flex-direction:column;align-items:flex-start;gap:24px">
    <p style="font-size:13px;color:var(--mute)">Launch sale ends in</p>
    <div class="asta-countdown asta-countdown-lg" role="timer" data-asta-countdown="2026-12-31T23:59:59Z" aria-label="Launch sale ends in"><span class="asta-countdown-unit"><span class="asta-countdown-value" data-unit="d">00</span><span class="asta-countdown-label">Days</span></span><span class="asta-countdown-sep" aria-hidden="true">:</span><span class="asta-countdown-unit"><span class="asta-countdown-value" data-unit="h">00</span><span class="asta-countdown-label">Hours</span></span><span class="asta-countdown-sep" aria-hidden="true">:</span><span class="asta-countdown-unit"><span class="asta-countdown-value" data-unit="m">00</span><span class="asta-countdown-label">Min</span></span><span class="asta-countdown-sep" aria-hidden="true">:</span><span class="asta-countdown-unit"><span class="asta-countdown-value" data-unit="s">00</span><span class="asta-countdown-label">Sec</span></span></div>
    <div class="asta-countdown" role="timer" data-asta-countdown="2027-01-15T12:00:00Z" aria-label="Auction closes in"><span class="asta-countdown-unit"><span class="asta-countdown-value" data-unit="d">00</span><span class="asta-countdown-label">Days</span></span><span class="asta-countdown-sep" aria-hidden="true">:</span><span class="asta-countdown-unit"><span class="asta-countdown-value" data-unit="h">00</span><span class="asta-countdown-label">Hours</span></span><span class="asta-countdown-sep" aria-hidden="true">:</span><span class="asta-countdown-unit"><span class="asta-countdown-value" data-unit="m">00</span><span class="asta-countdown-label">Min</span></span></div>
    <div class="asta-countdown asta-countdown-inline" role="timer" data-asta-countdown="2027-03-01T00:00:00Z" aria-label="Seats held for"><span class="asta-countdown-unit"><span class="asta-countdown-value" data-unit="d">00</span><span class="asta-countdown-label">d</span></span><span class="asta-countdown-sep" aria-hidden="true"> </span><span class="asta-countdown-unit"><span class="asta-countdown-value" data-unit="h">00</span><span class="asta-countdown-label">h</span></span><span class="asta-countdown-sep" aria-hidden="true"> </span><span class="asta-countdown-unit"><span class="asta-countdown-value" data-unit="m">00</span><span class="asta-countdown-label">m</span></span><span class="asta-countdown-sep" aria-hidden="true"> </span><span class="asta-countdown-unit"><span class="asta-countdown-value" data-unit="s">00</span><span class="asta-countdown-label">s</span></span></div>
    </div>

Usage

The demo above, as code.

"use client";

import { useState } from "react";
import { Button } from "@/components/astabyte/button";
import { Countdown } from "@/components/astabyte/countdown";

const Label = ({ children }: { children: React.ReactNode }) => <p className="font-mono text-[11px] uppercase tracking-wider text-mute">{children}</p>;

export default function CountdownDemo() {
  // Fixed offsets from when the demo mounts, so the page always shows a live timer.
  const [base] = useState(() => Date.now());
  const [resendAt, setResendAt] = useState(() => Date.now() + 12_000);
  const [canResend, setCanResend] = useState(false);

  const resend = () => {
    setCanResend(false);
    setResendAt(Date.now() + 12_000);
  };

  return (
    <div className="flex min-h-[460px] w-full items-center justify-center p-6 sm:p-10">
      <div className="flex w-full max-w-[560px] flex-col gap-9">
        <div className="flex flex-col items-center gap-4 text-center">
          <Label>Launch sale ends in</Label>
          <Countdown to={base + 2 * 86_400_000 + 7 * 3_600_000 + 42 * 60_000 + 9_000} size="lg" label="Launch sale ends in" className="max-sm:hidden" />
          <Countdown to={base + 2 * 86_400_000 + 7 * 3_600_000 + 42 * 60_000 + 9_000} size="md" label="Launch sale ends in" className="sm:hidden" />
        </div>

        <div className="grid gap-3 sm:grid-cols-2">
          <div className="flex items-center justify-between gap-3 rounded-xl bg-paper-2 px-4 py-3.5">
            <div className="min-w-0">
              <p className="text-[13.5px] font-medium text-ink">Lot 24 · Studio chair</p>
              <p className="text-[12px] text-mute">Bidding closes in</p>
            </div>
            <Countdown to={base + 4 * 60_000 + 59_000} units={["m", "s"]} variant="inline" size="sm" label="Bidding closes in" />
          </div>
          <div className="flex items-center justify-between gap-3 rounded-xl bg-paper-2 px-4 py-3.5">
            <div className="min-w-0">
              <p className="text-[13.5px] font-medium text-ink">Hold your seats</p>
              <p className="text-[12px] text-mute">Reserved for</p>
            </div>
            <Countdown to={base + 9 * 60_000 + 30_000} units={["m", "s"]} size="sm" label="Seats reserved for" />
          </div>
        </div>

        <div className="flex flex-col items-center gap-2 text-center">
          <p className="text-[13px] text-mute">We sent a code to [email protected]</p>
          {canResend ? (
            <Button size="sm" variant="outline" onClick={resend}>
              Resend code
            </Button>
          ) : (
            <p className="flex h-8 items-center gap-1.5 text-[13px] text-ink-2">
              Resend in
              <Countdown key={resendAt} to={resendAt} units={["m", "s"]} variant="inline" size="sm" label="Resend available in" onComplete={() => setCanResend(true)} className="text-[13px]" />
            </p>
          )}
        </div>
      </div>
    </div>
  );
}