phanpy/src/utils/useInterval.js

23 lines
581 B
JavaScript
Raw Normal View History

import { useEffect, useRef } from 'preact/hooks';
2023-05-05 12:53:16 +03:00
function useInterval(fn, delay, deps, immediate) {
const savedCallback = useRef(fn);
useEffect(() => {
2023-05-05 12:53:16 +03:00
savedCallback.current = fn;
}, [deps]);
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;