Skip to content

Instantly share code, notes, and snippets.

@tobx
Created December 27, 2021 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobx/d893396cd7d6d115169a82f9ea6702c0 to your computer and use it in GitHub Desktop.
Save tobx/d893396cd7d6d115169a82f9ea6702c0 to your computer and use it in GitHub Desktop.
Async version of requestAnimationFrame and animation loop
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