forked from vueComponent/ant-design-vue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathraf.ts
47 lines (37 loc) · 1.02 KB
/
raf.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
41
42
43
44
45
46
47
let raf = (callback: FrameRequestCallback) => setTimeout(callback, 16) as any;
let caf = (num: number) => clearTimeout(num);
if (typeof window !== 'undefined' && 'requestAnimationFrame' in window) {
raf = (callback: FrameRequestCallback) => window.requestAnimationFrame(callback);
caf = (handle: number) => window.cancelAnimationFrame(handle);
}
let rafUUID = 0;
const rafIds = new Map<number, number>();
function cleanup(id: number) {
rafIds.delete(id);
}
export default function wrapperRaf(callback: () => void, times = 1): number {
rafUUID += 1;
const id = rafUUID;
function callRef(leftTimes: number) {
if (leftTimes === 0) {
// Clean up
cleanup(id);
// Trigger
callback();
} else {
// Next raf
const realId = raf(() => {
callRef(leftTimes - 1);
});
// Bind real raf id
rafIds.set(id, realId);
}
}
callRef(times);
return id;
}
wrapperRaf.cancel = (id: number) => {
const realId = rafIds.get(id);
cleanup(realId);
return caf(realId);
};