UNPKG

animation-frame-loop

Version:

A small wrapper to take care of tracking delta time between frames. Useful for animations or other frame reliant things.

41 lines (40 loc) 1.29 kB
export class AnimationFrameLoop { callback; request = 0; lastTime = 0; totalElapsedTime = 0; totalFrameCountInSecond = 0; currentFps = 0; lastFpsUpdate = 0; constructor(callback) { this.callback = callback; if (this.request) return; const frame = (currentTime) => { const deltaTime = (currentTime - this.lastTime) / 1000; this.totalElapsedTime += deltaTime; this.lastTime = currentTime; this.totalFrameCountInSecond++; if (currentTime - this.lastFpsUpdate >= 1000) { this.currentFps = this.totalFrameCountInSecond; this.totalFrameCountInSecond = 0; this.lastFpsUpdate = currentTime; } const time = { totalElapsedTime: this.totalElapsedTime, currentFps: this.currentFps, deltaTime }; this.callback(time); this.request = requestAnimationFrame(frame); }; this.lastTime = performance.now(); this.request = requestAnimationFrame(frame); } destroy() { if (!this.request) return; cancelAnimationFrame(this.request); this.request = 0; } }