Skip to content

Instantly share code, notes, and snippets.

@alexreardon
Created March 21, 2023 00:19
Show Gist options
  • Save alexreardon/3c400f9bc55810c7e084894d978ea9aa to your computer and use it in GitHub Desktop.
Save alexreardon/3c400f9bc55810c7e084894d978ea9aa to your computer and use it in GitHub Desktop.
a function that lets you wait for animation frames to be called before executing a function
function waitForFrames({
frames,
done,
}: {
frames: number;
done: () => void;
}): () => void {
let frameId: number | null = null;
let remainingFrames = frames;
function scheduleFrame() {
if (remainingFrames <= 0) {
frameId = null;
done();
return;
}
frameId = requestAnimationFrame(() => {
remainingFrames--;
scheduleFrame();
});
}
scheduleFrame();
return function cleanup() {
if (frameId != null) {
cancelAnimationFrame(frameId);
frameId = null;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment