Skip to content

Instantly share code, notes, and snippets.

@Nate-Wilkins
Last active October 12, 2023 01:20
Show Gist options
  • Save Nate-Wilkins/790c49d030953fca84b1f467010a0b14 to your computer and use it in GitHub Desktop.
Save Nate-Wilkins/790c49d030953fca84b1f467010a0b14 to your computer and use it in GitHub Desktop.
createAnimationFrame.ts
/*
* Create an animation frame with a specified callback with
* a target frame rate.
*/
const createAnimationFrame = (
callback: (timeDelta: number) => boolean,
targetFrameRate?: number,
timePrevious?: number,
timeCurrent?: number,
): null | number => {
if (typeof timePrevious === 'number' && typeof timeCurrent === 'number') {
const timeDelta = timeCurrent - timePrevious;
if (
typeof targetFrameRate !== 'number' ||
timeDelta >= 1000 / targetFrameRate
) {
const success = callback(timeDelta);
if (!success) {
return null;
}
timePrevious = timeCurrent;
}
} else {
timePrevious = timeCurrent;
}
return window.requestAnimationFrame(timeCurrent =>
this.createAnimationFrame(
callback,
targetFrameRate,
timePrevious,
timeCurrent,
),
);
};
// Usage:
createAnimationFrame(
timeDelta => {
// Do stuff...
return true;
},
120
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment