2020-10-13 14:26:56 +00:00
|
|
|
interface RafMap {
|
|
|
|
[id: number]: number;
|
|
|
|
}
|
|
|
|
|
2020-09-30 09:35:51 +00:00
|
|
|
let id = 0;
|
2020-10-13 14:26:56 +00:00
|
|
|
const ids: RafMap = {};
|
2018-12-13 13:26:21 +00:00
|
|
|
|
|
|
|
// Support call raf with delay specified frame
|
2021-10-26 09:48:54 +00:00
|
|
|
export default function raf(callback: () => void, delayFrames = 1): number {
|
2020-10-13 14:26:56 +00:00
|
|
|
const myId: number = id++;
|
|
|
|
let restFrames: number = delayFrames;
|
2018-12-13 13:26:21 +00:00
|
|
|
|
2019-01-12 03:33:27 +00:00
|
|
|
function internalCallback() {
|
|
|
|
restFrames -= 1;
|
2018-12-13 13:26:21 +00:00
|
|
|
|
|
|
|
if (restFrames <= 0) {
|
2019-01-12 03:33:27 +00:00
|
|
|
callback();
|
2020-03-07 11:45:13 +00:00
|
|
|
delete ids[myId];
|
2018-12-13 13:26:21 +00:00
|
|
|
} else {
|
2021-01-07 04:53:49 +00:00
|
|
|
ids[myId] = requestAnimationFrame(internalCallback);
|
2018-12-13 13:26:21 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-07 04:53:49 +00:00
|
|
|
ids[myId] = requestAnimationFrame(internalCallback);
|
2018-12-13 13:26:21 +00:00
|
|
|
|
2019-01-12 03:33:27 +00:00
|
|
|
return myId;
|
2018-12-13 13:26:21 +00:00
|
|
|
}
|
|
|
|
|
2021-10-26 09:48:54 +00:00
|
|
|
raf.cancel = function cancel(pid?: number) {
|
2020-03-07 11:45:13 +00:00
|
|
|
if (pid === undefined) return;
|
2020-10-13 14:26:56 +00:00
|
|
|
|
2021-01-07 04:53:49 +00:00
|
|
|
cancelAnimationFrame(ids[pid]);
|
2019-03-07 05:26:03 +00:00
|
|
|
delete ids[pid];
|
2019-01-12 03:33:27 +00:00
|
|
|
};
|
2020-10-13 14:26:56 +00:00
|
|
|
|
2021-10-26 09:48:54 +00:00
|
|
|
raf.ids = ids; // export this for test usage
|