Created
August 3, 2018 14:42
-
-
Save zerobias/a8a6787c33e1d197ee3acbaf949ce859 to your computer and use it in GitHub Desktop.
requestAnimationFrame based scheduler
This file contains hidden or 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
// @flow | |
type WrapperFn = (...args: mixed[]) => void; | |
type CancelFn = {| | |
cancel: () => void, | |
|}; | |
type ResultFn = WrapperFn & CancelFn; | |
export default (fn: Function): ResultFn => { | |
let lastArgs: mixed[] = []; | |
let frameId: ?AnimationFrameID = null; | |
const wrapperFn: WrapperFn = (...args: mixed[]): void => { | |
// Always capture the latest value | |
lastArgs = args; | |
// There is already a frame queued | |
if (frameId) { | |
return; | |
} | |
// Schedule a new frame | |
frameId = requestAnimationFrame(() => { | |
frameId = null; | |
fn(...lastArgs); | |
}); | |
}; | |
// Adding cancel property to result function | |
wrapperFn.cancel = () => { | |
if (!frameId) { | |
return; | |
} | |
cancelAnimationFrame(frameId); | |
frameId = null; | |
}; | |
const resultFn: ResultFn = (wrapperFn: any); | |
return resultFn; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment