ant-design-vue/components/_util/raf.ts

48 lines
1.0 KiB
TypeScript
Raw Normal View History

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