Docs
useCountdown
Create countdown timers using useCountdown.
Loading...
Installation
pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-countdown
Usage
"use client"
import * as React from "react"
import { useIntervalWhen } from "@/hooks/use-interval-when"
export function Component() {
const [endTime, setEndTime] = React.useState(new Date(Date.now() + 10000))
const [complete, setComplete] = React.useState(false)
const count = useCountdown(endTime, {
interval: 1000,
onTick: (time) =>
console.log(`Tick: ${Math.round(time / 1000)}s remaining`),
onComplete: () => setComplete(true),
})
const handleClick = (additionalTime: number) => {
if (complete) return
const newEndTime = endTime.getTime() + additionalTime
setEndTime(new Date(newEndTime))
}
const formatTime = (milliseconds: number): string => {
const seconds = Math.ceil(milliseconds / 1000)
return `${seconds}s`
}
return (
<section>
<h1>Countdown Timer</h1>
<div className="countdown">
{complete ? "Complete!" : formatTime(count)}
</div>
{!complete && (
<div className="controls">
<button onClick={() => handleClick(5000)}>+5s</button>
<button onClick={() => handleClick(10000)}>+10s</button>
<button onClick={() => handleClick(15000)}>+15s</button>
</div>
)}
</section>
)
}
API Reference
Parameters
Name | Type | Description | Default Value | Optional |
---|---|---|---|---|
endTime | number | The end time of the countdown in milliseconds since the Unix epoch. | - | No |
options | object | An object containing the following options | - | Yes |
options.interval | number | The interval in milliseconds at which the countdown should tick. | 1000 | Yes |
options.onComplete | Function | A callback function to be called when the countdown reaches zero. | - | Yes |
options.onTick | Function | A callback function to be called on each tick of the countdown. | - | Yes |
Return Values
Name | Type | Description |
---|---|---|
count | number | The current count of the countdown. |