UNPKG

@rooks/use-timeout-when

Version:

Takes a callback and fires it when a condition is true

30 lines (27 loc) 924 B
import { useRef, useEffect } from 'react'; /** * A setTimeout hook that calls a callback after a timeout duration * when a condition is true * @param cb The callback to be invoked after timeout * @param timeoutDelayMs Amount of time in ms after which to invoke * @param when The condition which when true, sets the timeout */ function useTimeoutWhen(cb, timeoutDelayMs = 0, when = true) { const savedRefCallback = useRef(); useEffect(() => { savedRefCallback.current = cb; }); function callback() { savedRefCallback.current && savedRefCallback.current(); } useEffect(() => { if (when) { const timeout = window.setTimeout(callback, timeoutDelayMs); return () => { window.clearTimeout(timeout); }; } }, [when]); } export default useTimeoutWhen; //# sourceMappingURL=index.esm.js.map