useInterval
- This is a hook that provides functions related to JavaScript's
setInterval.
Features
-
You can provide the options
clearOnExistandexitOnExistto control how to handle an already runningsetInterval. -
Note that both
clearOnExistandexitOnExistcannot be set to false simultaneously. -
It accepts a
callbackfunction and a delay time inms, just likesetInterval. -
You can set it to execute after the DOM render by providing a boolean value to
immediate. -
The
callbackandmspassed to the hook are set as default values for the returnedinterval, but they can be overridden with a newcallbackand delay time inmsfor the interval."
Types
type TimeOptions = { clearOnExist: true; exitOnExist?: boolean } | { clearOnExist?: boolean; exitOnExist: true };
interface UseTimeParams {
callback?: () => void;
ms?: number;
immediate?: boolean;
setTimeHandler: typeof setInterval | typeof setTimeout;
clearTime: typeof clearInterval | typeof clearTimeout;
}
interface TimeCallbackParams extends Pick<Partial<UseTimeParams>, 'callback' | 'ms'> {
options?: TimeOptions;
}
const useInterval: (params?: Omit<UseTimeParams, 'setTimeHandler' | 'clearTime'>) => {
interval: (params?: TimeCallbackParams) => NodeJS.Timeout | null;
clear: () => void;
};
Example
const Ellipsis = ({
circleTotal = 10,
firstDelay = 5,
lastDelay = 5,
showedCircleTotal = 3,
slow = 100,
size,
}: EllipsisProps) => {
const [count, setCount] = useState(-firstDelay);
const circleTotalArray = Array.from({ length: circleTotal });
useInterval({
callback: () => {
const maxDelay = circleTotal + showedCircleTotal + lastDelay;
setCount(prev => (prev === maxDelay ? -firstDelay : prev + 1));
},
ms: slow,
immediate: true,
});
};