-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
fcabb29
commit 8ed3292
Showing
2 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
let raf = (callback: FrameRequestCallback) => +setTimeout(callback, 16) | ||
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) | ||
} | ||
|
||
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(id) | ||
return caf(realId!) | ||
} | ||
|
||
export default wrapperRaf |