Skip to content

Commit

Permalink
feat(shared): add raf utils
Browse files Browse the repository at this point in the history
  • Loading branch information
wangxingkang committed May 30, 2024
1 parent fcabb29 commit 8ed3292
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/shared/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export * from './utils'
export * from './uuid'
export * from './dedent'
export * from './indent'
export { default as raf } from './raf'
export {
// Array
alphabetical,
Expand Down
51 changes: 51 additions & 0 deletions packages/shared/raf/index.ts
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

0 comments on commit 8ed3292

Please sign in to comment.