Use Timeout

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

Preview

Loading...

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 useTimeout = (
callback: () => void,
delay: number | null,
): void => {
const savedCallback = React.useRef(callback);
React.useEffect(() => {
savedCallback.current = callback;
}, [callback]);
React.useEffect(() => {
if (delay === null || typeof delay !== 'number') return;
const tick = () => savedCallback.current();
const id = setTimeout(tick, delay);
return () => clearTimeout(id);
}, [delay]);
};

Update the import paths to match your project setup

Usage

import { useTimeout } 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 timeout.