Skip to main content

useTimeout

  • This is a hook that provides functions related to JavaScript's setTimeout.

Features

  • You can provide the options clearOnExist and exitOnExist to control how to handle an already running setTimeout.

  • Note that both clearOnExist and exitOnExist cannot be set to false simultaneously.

  • It accepts a callback function and a delay time in ms, just like setTimeout.

  • You can set it to execute after the DOM render by providing a boolean value to immediate.

  • The callback and ms passed to the hook are set as default values for the returned interval, but they can be overridden with a new callback and delay time in ms for 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 });
};