@react-md/utils
Version:
General utils for react-md.
50 lines • 1.91 kB
JavaScript
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 { useEffect } from "react";
import { useRefCache } from "./useRefCache";
import { useToggle } from "./useToggle";
/**
* Simple hook to use an interval with auto setup and teardown. The provided
* functions will be guaranteed to not change and are memoized.
*
* @param callback - The callback function to call
* @param delay - The time in milliseconds the timer should delay between
* executions of the callback function
* @param defaultRunning - Boolean if the interval should be started immediately
* @returns a list containing a boolean if the interval is running, function to
* start the interval, and a function to stop the interval.
*/
export function useInterval(callback, delay, defaultRunning) {
if (defaultRunning === void 0) { defaultRunning = false; }
var ref = useRefCache(callback);
var _a = __read(useToggle(defaultRunning), 3), running = _a[0], start = _a[1], stop = _a[2];
useEffect(function () {
if (!running) {
return;
}
var interval = window.setInterval(function () {
ref.current(stop);
}, delay);
return function () {
window.clearInterval(interval);
};
// disabled since useRefCache for the callback
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [delay, running, stop]);
return [running, start, stop];
}
//# sourceMappingURL=useInterval.js.map