useInterval
zyeon/use-intervalFreeHook
A declarative setInterval hook with a nullable delay, an always-fresh callback, and pause/resume controls.
See it running
Open the demo on zyeon
ui.zyeon.ai/r/use-intervalInstall it
npx shadcn@latest add https://ui.zyeon.ai/r/use-interval.jsonSource
1"use client"23import * as React from "react"45export interface UseIntervalOptions {6 /** interval 每次被(重新)建立时先同步执行一次 callback:挂载、resume、delay 变化。默认 false。 */7 immediate?: boolean8}910export interface UseIntervalControls {11 /** 停表:清掉当前 interval,`isPaused` 变 true。 */12 pause: () => void13 /** 继续:按当前 `delay` 重新建 interval(`immediate` 为 true 时先执行一次)。 */14 resume: () => void15 isPaused: boolean16}1718/**19 * 声明式的 `setInterval`:`delay` 传 `null` 即暂停(不建计时器),另返回20 * `{ pause, resume, isPaused }` 给需要按钮控制的场景。21 *22 * 核心是**最新 callback 存 ref**:effect 每次渲染只更新 `savedCallback.current`,23 * 而建 interval 的 effect 依赖里根本没有 `callback` —— 于是消费者写内联箭头函数24 * (几乎总是如此,而且闭包里往往捕获着会变的 state)不会每次渲染都 clear + 重建25 * 计时器,节奏不会被重置,但每次 tick 调到的又永远是最新那份闭包。26 *27 * - `delay` 变化时重建 interval(新周期立即生效);`delay` 不变则计时器原样保留。28 * - `pause()` / `resume()` 走的是同一条重建路径:`isPaused` 是建 interval 那个29 * effect 的依赖,置 true 时 cleanup 清掉计时器,置 false 时重新建。30 * - **SSR 安全**:计时器只在 effect 里建,渲染期不碰任何浏览器 API;卸载时31 * `clearInterval` 必被调用,不会有 tick 打在已卸载的组件上。32 */33export function useInterval(34 callback: () => void,35 delay: number | null,36 options: UseIntervalOptions = {},37): UseIntervalControls {38 const { immediate = false } = options39 const [isPaused, setIsPaused] = React.useState(false)4041 const savedCallback = React.useRef(callback)42 React.useEffect(() => {43 savedCallback.current = callback44 })4546 React.useEffect(() => {47 if (delay === null || isPaused) return4849 if (immediate) savedCallback.current()5051 const id = setInterval(() => savedCallback.current(), delay)52 return () => clearInterval(id)53 }, [delay, isPaused, immediate])5455 const pause = React.useCallback(() => setIsPaused(true), [])56 const resume = React.useCallback(() => setIsPaused(false), [])5758 return { pause, resume, isPaused }59}6061export default useInterval
Files it writes
More from zyeon
All 517 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| useAsyncuse-async | zyeon | Hooks | Free | no deps | |
| useBroadcastChanneluse-broadcast-channel | zyeon | Hooks | Free | no deps | |
| useClickOutsideuse-click-outside | zyeon | Hooks | Free | no deps | |
| useClipboardPasteuse-clipboard-paste | zyeon | Hooks | Free | no deps | |
| useControllableStateuse-controllable-state | zyeon | Hooks | Free | no deps | |
| useCopyToClipboarduse-copy-to-clipboard | zyeon | Hooks | Free | no deps | |
| useCountdownuse-countdown | zyeon | Hooks | Free | no deps | |
| useDebounceValueuse-debounce-value | zyeon | Hooks | Free | no deps |
