useTimer
A flexible timer hook for creating stopwatches, countdowns, and interval-based timers with pause, resume, and reset functionality. Perfect for creating time-based interactions and animations.
Interactive Demo
00:00:00
Implementation
interface TimerOptions {
initialTime?: number;
interval?: number;
autostart?: boolean;
endTime?: number;
countdown?: boolean;
onEnd?: () => void;
}
export function useTimer({
initialTime = 0,
interval = 1000,
autostart = false,
endTime,
countdown = false,
onEnd,
}: TimerOptions = {}) {
const [time, setTime] = useState(initialTime);
const [isRunning, setIsRunning] = useState(autostart);
const start = useCallback(() => setIsRunning(true), []);
const pause = useCallback(() => setIsRunning(false), []);
const reset = useCallback(() => {
setIsRunning(false);
setTime(initialTime);
}, [initialTime]);
const toggle = useCallback(() => {
setIsRunning((prev) => !prev);
}, []);
useEffect(() => {
if (!isRunning) return;
const intervalId = setInterval(() => {
setTime((currentTime) => {
const newTime = countdown ? currentTime - interval : currentTime + interval;
if (endTime !== undefined) {
if ((countdown && newTime <= endTime) || (!countdown && newTime >= endTime)) {
setIsRunning(false);
onEnd?.();
return endTime;
}
}
return newTime;
});
}, interval);
return () => clearInterval(intervalId);
}, [isRunning, interval, endTime, countdown, onEnd]);
return {
time,
isRunning,
start,
pause,
reset,
toggle,
} as const;
}
Usage Examples
import { useTimer } from '@/components/hooks/useTimer';
function TimerExample() {
const timer = useTimer({
initialTime: 0,
interval: 1000,
autostart: false,
});
return (
<div>
<div>Time: {timer.time}ms</div>
<button onClick={timer.toggle}>
{timer.isRunning ? 'Pause' : 'Start'}
</button>
<button onClick={timer.reset}>Reset</button>
</div>
);
}
Documentation
Key Features
- Configurable interval-based timing
- Support for both countdown and stopwatch modes
- Pause, resume, and reset functionality
- Optional autostart capability
- Configurable end time
- TypeScript support
Common Use Cases
- Countdown timers
- Stopwatches
- Game timers
- Session timeout tracking
- Time-based animations
API Reference
useTimer(options?: TimerOptions)
Options:
- initialTime?: number (default: 0) - Starting time in milliseconds
- interval?: number (default: 1000) - Update interval in milliseconds
- autostart?: boolean (default: false) - Whether to start automatically
- endTime?: number - Optional end time for the timer
- countdown?: boolean (default: false) - Whether to count down instead of up
- onEnd?: () => void - Callback function executed when timer reaches endTime
Returns:
- time: number - Current time value
- isRunning: boolean - Timer running state
- start(): void - Start the timer
- pause(): void - Pause the timer
- reset(): void - Reset to initial time
- toggle(): void - Toggle between running and paused states