Created
December 27, 2021 13:40
-
-
Save tobx/d893396cd7d6d115169a82f9ea6702c0 to your computer and use it in GitHub Desktop.
Async version of requestAnimationFrame and animation loop
This file contains 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
export class Frame { | |
constructor() { | |
this.requestId = 0; | |
} | |
cancel() { | |
window.cancelAnimationFrame(this.requestId); | |
this.requestId = 0; | |
} | |
isRequested() { | |
return this.requestId > 0; | |
} | |
async request() { | |
return new Promise((resolve) => { | |
this.requestId = window.requestAnimationFrame(resolve); | |
}); | |
} | |
} | |
export class Loop { | |
constructor(update) { | |
this.update = update; | |
this.frame = new Frame(); | |
this.lastFrameStart = 0; | |
} | |
isPlaying() { | |
return this.frame.isRequested(); | |
} | |
async play() { | |
if (this.isPlaying()) return; | |
let frameStart = window.performance.now(); | |
while (true) { | |
const timestamp = await this.frame.request(); | |
this.update(timestamp - frameStart); | |
frameStart = timestamp; | |
} | |
} | |
pause() { | |
this.frame.cancel(); | |
} | |
} | |
function test() { | |
const loop = new Loop((elapsedTime) => { | |
console.log("frameDeltaTime: " + elapsedTime); | |
}); | |
loop.play(); | |
console.log("loop is running: ", loop.isPlaying()); | |
window.setTimeout(() => { | |
loop.pause(); | |
console.log("loop is running: ", loop.isPlaying()); | |
}, 1000); | |
} | |
test(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment