2022-04-23 01:48:03 +00:00
|
|
|
let raf = (callback: FrameRequestCallback) => setTimeout(callback, 16) as any;
|
2021-12-19 03:06:55 +00:00
|
|
|
let caf = (num: number) => clearTimeout(num);
|
2020-10-13 14:26:56 +00:00
|
|
|
|
2021-12-19 03:06:55 +00:00
|
|
|
if (typeof window !== 'undefined' && 'requestAnimationFrame' in window) {
|
|
|
|
raf = (callback: FrameRequestCallback) => window.requestAnimationFrame(callback);
|
|
|
|
caf = (handle: number) => window.cancelAnimationFrame(handle);
|
|
|
|
}
|
2018-12-13 13:26:21 +00:00
|
|
|
|
2021-12-19 03:06:55 +00:00
|
|
|
let rafUUID = 0;
|
|
|
|
const rafIds = new Map<number, number>();
|
|
|
|
|
|
|
|
function cleanup(id: number) {
|
|
|
|
rafIds.delete(id);
|
|
|
|
}
|
2018-12-13 13:26:21 +00:00
|
|
|
|
2021-12-19 03:06:55 +00:00
|
|
|
export default function wrapperRaf(callback: () => void, times = 1): number {
|
|
|
|
rafUUID += 1;
|
|
|
|
const id = rafUUID;
|
2018-12-13 13:26:21 +00:00
|
|
|
|
2021-12-19 03:06:55 +00:00
|
|
|
function callRef(leftTimes: number) {
|
|
|
|
if (leftTimes === 0) {
|
|
|
|
// Clean up
|
|
|
|
cleanup(id);
|
|
|
|
|
|
|
|
// Trigger
|
2019-01-12 03:33:27 +00:00
|
|
|
callback();
|
2018-12-13 13:26:21 +00:00
|
|
|
} else {
|
2021-12-19 03:06:55 +00:00
|
|
|
// Next raf
|
|
|
|
const realId = raf(() => {
|
|
|
|
callRef(leftTimes - 1);
|
|
|
|
});
|
|
|
|
|
|
|
|
// Bind real raf id
|
|
|
|
rafIds.set(id, realId);
|
2018-12-13 13:26:21 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-19 03:06:55 +00:00
|
|
|
callRef(times);
|
2018-12-13 13:26:21 +00:00
|
|
|
|
2021-12-19 03:06:55 +00:00
|
|
|
return id;
|
2018-12-13 13:26:21 +00:00
|
|
|
}
|
|
|
|
|
2021-12-19 03:06:55 +00:00
|
|
|
wrapperRaf.cancel = (id: number) => {
|
|
|
|
const realId = rafIds.get(id);
|
|
|
|
cleanup(realId);
|
|
|
|
return caf(realId);
|
2019-01-12 03:33:27 +00:00
|
|
|
};
|