Use Timeout

A hook that executes a callback function after a specified delay using the setTimeout API.

Preview

Installation

CLI

npx shadcn@latest add https://kelvinmai.io/r/use-timeout.json

Manual

Copy and paste the following code into your project

hooks/use-timeout.ts
'use client';
import * as React from 'react';
export const useInterval = (callback: () => void, delay: number | null) => {
const ref = React.useRef(callback);
React.useEffect(() => {
ref.current = callback;
}, [callback]);
React.useEffect(() => {
if (delay === null || typeof delay !== 'number') {
return;
}
const tick = () => ref.current();
const id = setInterval(tick, delay);
return () => clearInterval(id);
}, [delay]);
};

Update the import paths to match your project setup

Usage

import { useTimout } from '@/hooks/use-timeout';
useTimeout(() => {
func();
}, 1000);

API Reference

Parameters

NameTypeDescription
callback
() => void
The function to be invoked at the end of the delay.
delay
number | null
The duration time in milliseconds for the timeout. Use null to clear the interval.