useTimeout
A hook that creates a timeout.
Loading...
Installation
npx shadcn@latest add @hooks/use-timeoutpnpm dlx shadcn@latest add @hooks/use-timeoutyarn dlx shadcn@latest add @hooks/use-timeoutbun x shadcn@latest add @hooks/use-timeoutCopy and paste the following code into your project.
import { useMemo, useRef } from 'react'
type noop = (this: any, ...args: any[]) => any
type PickFunction<T extends noop> = (
this: ThisParameterType<T>,
...args: Parameters<T>
) => ReturnType<T>
export function useMemoizedFn<T extends noop>(fn: T) {
const fnRef = useRef<T>(fn)
// why not write `fnRef.current = fn`?
// https://github.com/alibaba/hooks/issues/728
fnRef.current = useMemo<T>(() => fn, [fn])
const memoizedFn = useRef<PickFunction<T>>(undefined)
if (!memoizedFn.current) {
memoizedFn.current = function (this, ...args) {
return fnRef.current.apply(this, args)
}
}
return memoizedFn.current
}import { useCallback, useEffect, useRef } from 'react'
import { useMemoizedFn } from '@/registry/hooks/use-memoized-fn'
export function useTimeout(fn: () => void, delay: number = 0) {
const fnRef = useMemoizedFn(fn)
const timerRef = useRef<number | null>(null)
const clear = useCallback(() => {
if (timerRef.current) {
clearTimeout(timerRef.current)
timerRef.current = null
}
}, [])
useEffect(() => {
if (delay < 0) return
timerRef.current = window.setTimeout(fnRef, delay)
return () => {
clear()
}
}, [delay])
return clear
}API
/**
* A hook that creates a timeout.
* @param fn - The function to execute after the timeout
* @param delay - The delay in milliseconds before the function is executed
* @returns A function to clear the timeout
*/
export function useTimeout(fn: () => void, delay: number = 0): () => voidCredits
Last updated on