Skip to content

Instantly share code, notes, and snippets.

@lokshunhung
Created May 19, 2025 05:08
Show Gist options
  • Save lokshunhung/edc2f7f23bba2166e15bac657cd25961 to your computer and use it in GitHub Desktop.
Save lokshunhung/edc2f7f23bba2166e15bac657cd25961 to your computer and use it in GitHub Desktop.
fps limited requestAnimationFrame
class Renderer {
#targetDelay: number;
#onTick: (elapsed: number) => void;
#lastTickTimestamp: number = 0;
#animationId?: number;
constructor(fps: number, onTick: (elapsed: number) => void) {
this.#targetDelay = 1_000 / fps;
this.#onTick = onTick;
}
get isTicking(): boolean {
return this.#animationId !== undefined;
}
start() {
if (this.#animationId !== undefined) return;
this.#animationId = window.requestAnimationFrame(timestamp => this.#tick(timestamp));
}
end() {
if (this.#animationId === undefined) return;
window.cancelAnimationFrame(this.#animationId);
}
#tick(timestamp: DOMHighResTimeStamp) {
this.#animationId = window.requestAnimationFrame(timestamp => this.#tick(timestamp));
const elapsed = timestamp - this.#lastTickTimestamp;
if (elapsed < this.#targetDelay) return;
this.#onTick(elapsed);
this.#lastTickTimestamp = timestamp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment