2023-01-13 10:30:09 +03:00
|
|
|
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);
|
2023-01-13 10:30:09 +03:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
savedCallback.current = callback;
|
2023-02-08 14:11:33 +03:00
|
|
|
}, []);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (!immediate || delay === null || delay === false) return;
|
|
|
|
savedCallback.current();
|
|
|
|
}, [immediate]);
|
2023-01-13 10:30:09 +03:00
|
|
|
|
|
|
|
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);
|
2023-01-13 10:30:09 +03:00
|
|
|
}, [delay]);
|
|
|
|
}
|
2023-02-08 14:11:33 +03:00
|
|
|
|
|
|
|
export default useInterval;
|