phanpy/src/utils/useInterval.js

23 lines
513 B
JavaScript
Raw Normal View History

// useInterval with Preact
import { useEffect, useRef } from 'preact/hooks';
export default function useInterval(callback, delay) {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}