/** * @file 定时器/计时器相关的 hooks */ import { useTimeout as useTimeoutOrigin } from 'ahooks' import { useEffect, useState } from 'react' /** * setTimeout Hook 实现 * 详细请看:https://ahooks.js.org/hooks/side-effect/use-timeout */ export const useTimeout = useTimeoutOrigin /** * 设置 setInterval * * @param interval - 间隔 * @param callback - 回调函数 * @param disabled - true 时会清理并暂停定时器 */ export const useSetInterval = ({ interval, callback, disabled, }: { interval: number callback: () => void disabled?: boolean }) => { useEffect(() => { if (!disabled) { const t = setInterval(callback, interval) return () => { clearInterval(t) } } return undefined }, [interval, callback, disabled]) } /** * 设置一个以秒为单位的倒计时。 * * @param seconds - 倒计时总秒数 * @param accuracy - 毫秒数,用于指定倒计时更新时间间隔,影响计时精度,默认 200ms * * @returns `{ seconds: 剩余秒数, isCounting: 是否正在倒计时, startCounting: 开始倒计时, stopCounting: 停止并重置倒计时 }` */ export const useCountDown = ({ seconds, accuracy = 200, }: { seconds: number accuracy?: number }) => { const [started, setStarted] = useState(false) const [startAt, setStartAt] = useState() const [left, setLeft] = useState(seconds) useEffect(() => { if (started) { setStartAt(Date.now()) setLeft(seconds) } else { setStartAt(undefined) } }, [seconds, started]) const callback = () => { if (started && startAt) { const now = Date.now() const l = Math.max(0, Math.round(seconds - (now - startAt) / 1000)) setLeft(l) setStarted(!!l) } } useSetInterval({ interval: accuracy, callback, disabled: !startAt, }) const startCounting = () => setStarted(true) const stopCounting = () => setStarted(false) return { seconds: left, isCounting: started, startCounting, stopCounting } } /** * 以指定间隔刷新并返回当前时间的 hook * * @param interval - 刷新间隔。-1 表示不刷新 * * @returns Date 类型的当前时间 */ export function useNow({ interval = 1000 }: { interval?: number } = {}) { const [now, setNow] = useState(() => new Date()) useSetInterval({ callback: () => { setNow(new Date()) }, interval, disabled: interval === -1, }) return now }