-
Notifications
You must be signed in to change notification settings - Fork 3
/
core.ts
35 lines (27 loc) · 916 Bytes
/
core.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
import { useCallback, useEffect, useRef } from 'react';
export const useAnimationFrame = <Fn extends (...args: Parameters<Fn>) => void>(
fn: Fn,
wait = 0,
): ((...args: Parameters<Fn>) => void) => {
const rafId = useRef(0);
const render = useCallback(
(...args: Parameters<Fn>) => {
// Reset previous animation before start new animation
cancelAnimationFrame(rafId.current);
const timeStart = performance.now();
const renderFrame = (timeNow: number) => {
// Call next rAF if time is not up
if (timeNow - timeStart < wait) {
rafId.current = requestAnimationFrame(renderFrame);
return;
}
fn(...args);
};
rafId.current = requestAnimationFrame(renderFrame);
},
[fn, wait],
);
// Call cancel animation after umount
useEffect(() => () => cancelAnimationFrame(rafId.current), []);
return render;
};