Skip to content

Instantly share code, notes, and snippets.

@mimshins
Last active June 10, 2024 20:05
Show Gist options
  • Select an option

  • Save mimshins/c331fc1a2e0e221301cfaf2c543feb80 to your computer and use it in GitHub Desktop.

Select an option

Save mimshins/c331fc1a2e0e221301cfaf2c543feb80 to your computer and use it in GitHub Desktop.
Animation Loop
export type FrameTicker = (deltaTime: number) => void;
/**
* Creates smooth animation frames.
*
* @param frameTicker This callback will be called on each frame.\
* The `deltaTime` argument specifies the time elapsed between the last frame
* and the one preceding it (in milliseconds).
* @returns Returns animation frames controller.
*/
const createAnimationFrames = (frameTicker: FrameTicker) => {
let prevTimestamp: number = -Infinity;
let rafReference: number = -Infinity;
const mainTicker: FrameRequestCallback = timestamp => {
const deltaTime = timestamp - prevTimestamp;
prevTimestamp = timestamp;
frameTicker(deltaTime);
rafReference = window.requestAnimationFrame(mainTicker);
};
const start = () => {
prevTimestamp = performance.now();
rafReference = window.requestAnimationFrame(mainTicker);
};
const stop = () => {
window.cancelAnimationFrame(rafReference);
};
return { start, stop };
};
export default createAnimationFrames;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment