phanpy/src/utils/useInterval.js

26 lines
610 B
JavaScript
Raw Normal View History

import { useEffect, useRef } from 'preact/hooks';
2023-02-08 14:11:33 +03:00
const noop = () => {};
function useInterval(callback, delay, immediate) {
const savedCallback = useRef(noop);
useEffect(() => {
savedCallback.current = callback;
2023-02-08 14:11:33 +03:00
}, []);
useEffect(() => {
if (!immediate || delay === null || delay === false) return;
savedCallback.current();
}, [immediate]);
useEffect(() => {
2023-02-08 14:11:33 +03:00
if (delay === null || delay === false) return;
const tick = () => savedCallback.current();
const id = setInterval(tick, delay);
return () => clearInterval(id);
}, [delay]);
}
2023-02-08 14:11:33 +03:00
export default useInterval;