-
Notifications
You must be signed in to change notification settings - Fork 0
/
useAnimationFrame.ts
40 lines (34 loc) · 1.08 KB
/
useAnimationFrame.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { useCallback, useEffect, useRef } from "react";
interface Options {
maxFPS?: number;
}
export default function useAnimationFrame(callback: FrameRequestCallback, options?: Options): void {
const previousTimeRef = useRef<DOMHighResTimeStamp>();
const requestRef = useRef<number>();
const maxFPS = options?.maxFPS;
const animate = useCallback(
(time: DOMHighResTimeStamp): void => {
if (previousTimeRef.current != null) {
const deltaTime = time - previousTimeRef.current;
if (!maxFPS || deltaTime > 1000 / maxFPS) {
callback(deltaTime);
previousTimeRef.current = time;
}
} else {
callback(0);
previousTimeRef.current = time;
}
requestRef.current = requestAnimationFrame(animate);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[callback]
);
useEffect(() => {
requestRef.current = requestAnimationFrame(animate);
return (): void => {
if (requestRef.current != null) {
cancelAnimationFrame(requestRef.current);
}
};
}, [animate]);
}