UNPKG

@react-md/utils

Version:
69 lines 2.49 kB
var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; import { useCallback, useEffect, useRef } from "react"; import { useRefCache } from "./useRefCache"; import { useToggle } from "./useToggle"; /** * Simple hook to use an timeout with auto setup and teardown. The provided * functions will be guaranteed to not change and are memoized. * * @param cb - The callback function to call * @param delay - The time in milliseconds the timer should delay between * executions of the callback function * @param defaultStarted - Boolean if the timeout should be started immediately. * @returns a list containing a function to start the timeout, a function to * stop the timeout, and a function to restart the timeout. */ export function useTimeout(cb, delay, defaultStarted) { if (defaultStarted === void 0) { defaultStarted = false; } var cbRef = useRefCache(cb); var delayRef = useRefCache(delay); var timeoutRef = useRef(); var _a = __read(useToggle(defaultStarted), 3), enabled = _a[0], start = _a[1], disable = _a[2]; var clearTimeout = useCallback(function () { window.clearTimeout(timeoutRef.current); timeoutRef.current = undefined; }, []); /* eslint-disable react-hooks/exhaustive-deps */ // these are all guaranteed to not change since using refs or non-updating // callbacks var restart = useCallback(function () { clearTimeout(); timeoutRef.current = window.setTimeout(function () { cbRef.current(); disable(); }, delayRef.current); }, []); var stop = useCallback(function () { clearTimeout(); disable(); }, []); useEffect(function () { if (!enabled) { return; } timeoutRef.current = window.setTimeout(function () { cbRef.current(); disable(); }, delay); return function () { clearTimeout(); }; }, [enabled, delay, disable]); return [start, stop, restart]; } //# sourceMappingURL=useTimeout.js.map