Created
May 19, 2025 05:08
-
-
Save lokshunhung/edc2f7f23bba2166e15bac657cd25961 to your computer and use it in GitHub Desktop.
fps limited requestAnimationFrame
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
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