forked from streamich/react-use
-
Notifications
You must be signed in to change notification settings - Fork 0
/
useRaf.ts
39 lines (33 loc) · 857 Bytes
/
useRaf.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
import { useLayoutEffect, useState } from 'react';
const useRaf = (ms: number = 1e12, delay: number = 0): number => {
const [elapsed, set] = useState<number>(0);
useLayoutEffect(() => {
let raf;
let timerStop;
let start;
const onFrame = () => {
const time = Math.min(1, (Date.now() - start) / ms);
set(time);
loop();
};
const loop = () => {
raf = requestAnimationFrame(onFrame);
};
const onStart = () => {
timerStop = setTimeout(() => {
cancelAnimationFrame(raf);
set(1);
}, ms);
start = Date.now();
loop();
};
const timerDelay = setTimeout(onStart, delay);
return () => {
clearTimeout(timerStop);
clearTimeout(timerDelay);
cancelAnimationFrame(raf);
};
}, [ms, delay]);
return elapsed;
};
export default useRaf;