useTimeout
- This is a hook that provides functions related to JavaScript's
setTimeout.
Features
-
You can provide the options
clearOnExistandexitOnExistto control how to handle an already runningsetTimeout. -
Note that both
clearOnExistandexitOnExistcannot be set to false simultaneously. -
It accepts a
callbackfunction and a delay time inms, just likesetTimeout. -
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 useTimeout: (params?: Omit<UseTimeParams, 'setTimeHandler' | 'clearTime'>) => {
timeout: (params?: TimeCallbackParams) => NodeJS.Timeout | null;
clear: () => void;
};
Example
const Snackbar = (/**...**/) => {
useTimeout({ callback: close, ms: delay, immediate: true });
};