UNPKG

@rooks/use-interval

Version:

A react hook for using setInterval

58 lines (55 loc) 1.84 kB
import { useRef, useState, useEffect } from 'react'; // See also: https://overreacted.io/making-setinterval-declarative-with-react-hooks/ /** * * useInterval hook * * Declaratively creates a setInterval to run a callback after a fixed * amount of time * *@param {funnction} callback - Callback to be fired *@param {number} intervalId - Interval duration in milliseconds after which the callback is to be fired *@param {boolean} startImmediate - Whether the interval should start immediately on initialise *@return {IntervalHandler} */ function useInterval(callback, intervalDuration, startImmediate = false) { const internalIdRef = useRef(null); const [isRunning, setIsRunning] = useState(startImmediate); const savedCallback = useRef(); function start() { if (!isRunning) { setIsRunning(true); } } function stop() { if (isRunning) { setIsRunning(false); } } // Remember the latest callback. useEffect(() => { savedCallback.current = callback; }); // Set up the interval. useEffect(() => { function tick() { savedCallback.current && savedCallback.current(); } if (intervalDuration !== null && isRunning) { let id = setInterval(tick, intervalDuration); internalIdRef.current = id; return () => { internalIdRef.current = null; clearInterval(id); }; } }, [intervalDuration, isRunning]); let handler; handler = [start, stop, internalIdRef.current]; handler.start = start; handler.stop = stop; handler.intervalId = internalIdRef.current; return handler; } export default useInterval; //# sourceMappingURL=index.esm.js.map