Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

raf support weakset #280

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 57 additions & 10 deletions src/raf.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,30 @@
const hasWin = typeof window !== 'undefined';
const hasRaf = hasWin && typeof window.requestAnimationFrame !== 'undefined';
const hasWeakSet = hasWin && typeof window.WeakSet !== 'undefined';

let raf = (callback: FrameRequestCallback) => +setTimeout(callback, 16);
let caf = (num: number) => clearTimeout(num);

if (typeof window !== 'undefined' && 'requestAnimationFrame' in window) {
if (hasRaf) {
raf = (callback: FrameRequestCallback) =>
window.requestAnimationFrame(callback);
caf = (handle: number) => window.cancelAnimationFrame(handle);
}

let rafUUID = 0;
const rafIds = new Map<number, number>();
const rafKeys = new WeakSet<number[]>();

function cleanup(id: number) {
rafIds.delete(id);
}
const cleanupByMap = (id: number) => rafIds.delete(id);

export default function wrapperRaf(callback: () => void, times = 1): number {
const useRafByMap = (callback: () => void, times = 1): number => {
rafUUID += 1;
const id = rafUUID;

function callRef(leftTimes: number) {
if (leftTimes === 0) {
// Clean up
cleanup(id);
cleanupByMap(id);

// Trigger
callback();
Expand All @@ -39,10 +42,54 @@ export default function wrapperRaf(callback: () => void, times = 1): number {
callRef(times);

return id;
}
};

wrapperRaf.cancel = (id: number) => {
const realId = rafIds.get(id);
cleanup(realId);
useRafByMap.cancel = (key: number) => {
const realId = rafIds.get(key);
cleanupByMap(key);
return caf(realId);
};

const cleanupByWeakSet = (key: number[] | number): number => {
let oldKey = typeof key === "number" ? [+key] : key;
const [timeId] = oldKey || [];
if (timeId) {
caf(timeId);
rafKeys.delete(oldKey);
oldKey = null;
}
return timeId;
};

const useRafByWeakSet = (callback: () => void, times = 1): number => {
let key: number[];

function callRef(leftTimes: number) {
if (leftTimes === 0) {
// Clean up
cleanupByWeakSet(key);

// Trigger
callback();
} else {
// Next raf
key = [
raf(() => {
callRef(leftTimes - 1);
}),
];

// Bind real raf id
rafKeys.add(key);
}
}

callRef(times);

return +key;
};

useRafByWeakSet.cancel = (key: number[]) => cleanupByWeakSet(key);
const useRaf = hasWeakSet ? useRafByWeakSet : useRafByMap;

export default useRaf;