UNPKG

@rooks/use-interval

Version:

A react hook for using setInterval

64 lines (60 loc) 2.3 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) : typeof define === 'function' && define.amd ? define(['react'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.useInterval = factory(global.React)); }(this, (function (react) { 'use strict'; // 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 = react.useRef(null); const [isRunning, setIsRunning] = react.useState(startImmediate); const savedCallback = react.useRef(); function start() { if (!isRunning) { setIsRunning(true); } } function stop() { if (isRunning) { setIsRunning(false); } } // Remember the latest callback. react.useEffect(() => { savedCallback.current = callback; }); // Set up the interval. react.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; } return useInterval; }))); //# sourceMappingURL=index.js.map