mirror of
https://github.com/idanoo/GoScrobble.git
synced 2024-11-24 09:25:15 +00:00
38 lines
985 B
JavaScript
38 lines
985 B
JavaScript
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; |