Loading...
Please waitLoading...
Please waitpnpm dlx uselab@latest add use-countdown
import * as React from "react"
import { useCountdown } from "@/hooks/use-countdown"
export function Component() {
const [endTime, setEndTime] = React.useState(new Date(Date.now() + 10000))
const [complete, setComplete] = React.useState(false)
const { remaining, isPaused, pause, resume } = 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(remaining)}
</div>
<div className="controls">
<button
type="button"
disabled={complete}
onClick={() => (isPaused ? resume() : pause())}
>
{isPaused ? "Resume" : "Pause"}
</button>
</div>
{!complete && !isPaused && (
<div className="controls">
<button onClick={() => handleClick(5000)}>+5s</button>
<button onClick={() => handleClick(10000)}>+10s</button>
<button onClick={() => handleClick(15000)}>+15s</button>
</div>
)}
</section>
)
}| 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 |
| Name | Type | Description |
|---|---|---|
remaining | number | Milliseconds until endTime (≤0 when finished). Unchanged while paused. |
isPaused | boolean | Whether the countdown is paused. |
pause | () => void | Stop ticking; remaining stays on screen. |
resume | () => void | Start ticking again; pause time does not reduce the countdown (effective end shifts). |
Set countdown length — Apply starts from now
Reset clears completion, sets a fresh 1-minute countdown, and restores amount (1) and unit (minutes). +5s / +10s / +15s add to the current end time. Pause freezes the timer; Resume continues from the same remaining time.
Check the console to see the countdown tick every second.