GoScrobble/web/node_modules/@restart/hooks/esm/useRafInterval.js

38 lines
985 B
JavaScript
Raw Permalink Normal View History

2022-04-25 02:47:15 +00:00
import { useEffect } from 'react';
import useCommittedRef from './useCommittedRef';
function useRafInterval(fn, ms, paused) {
if (paused === void 0) {
paused = false;
}
var handle;
var start = new Date().getTime();
var fnRef = useCommittedRef(fn); // this ref is necessary b/c useEffect will sometimes miss a paused toggle
// orphaning a setTimeout chain in the aether, so relying on it's refresh logic is not reliable.
var pausedRef = useCommittedRef(paused);
function loop() {
var current = new Date().getTime();
var delta = current - start;
if (pausedRef.current) return;
if (delta >= ms && fnRef.current) {
fnRef.current();
start = new Date().getTime();
}
cancelAnimationFrame(handle);
handle = requestAnimationFrame(loop);
}
useEffect(function () {
handle = requestAnimationFrame(loop);
return function () {
return cancelAnimationFrame(handle);
};
}, []);
}
export default useRafInterval;