Created
March 21, 2023 00:19
-
-
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
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
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