import { useEffect, useState } from "react" type UseCountWithIntervalProps = { max?: number paused?: boolean increase?: boolean intervalMs?: number } export function useCountWithInterval( initialCount: number, { max, paused, increase = true, intervalMs }: UseCountWithIntervalProps, ) { const [count, setCount] = useState(initialCount) useEffect(() => { if (paused) { return } const interval = setInterval(() => { setCount(p => increase ? Math.min(p + 1, max || Infinity) : Math.max(p - 1, 0), ) }, intervalMs) return () => clearInterval(interval) }, [increase, intervalMs, max, paused]) return count } export function useTick(enabled: boolean, intervalMs: number) { return useCountWithInterval(0, { paused: !enabled, intervalMs, }) }