Last active
October 18, 2022 10:19
-
-
Save richardscarrott/5d8eee84481a73688588ba584f9c2ff8 to your computer and use it in GitHub Desktop.
Utility to enqueue + cancel callback for *next* animation frame (Double rAF)
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
const requestNextAnimationFrame = (callback: FrameRequestCallback) => { | |
const handles: number[] = []; | |
const requestThisAnimationFrame = (callback: FrameRequestCallback) => { | |
handles.push(window.requestAnimationFrame(callback)); | |
}; | |
requestThisAnimationFrame(() => requestThisAnimationFrame(callback)); | |
return () => handles.forEach(handle => window.cancelAnimationFrame(handle)); | |
}; | |
const box = document.createElement('div'); | |
document.body.prepend(box); | |
box.style.width = '100px'; | |
box.style.height = '100px'; | |
box.style.background = 'tomato'; | |
box.style.opacity = '0'; | |
box.style.transition = 'opacity 1s ease-in-out'; | |
const cancel = requestNextAnimationFrame(() => { | |
box.style.opacity = '1'; | |
}); | |
// cancel(); // <-- cancels the outer callback (inner is therefore never enqueued) | |
window.requestAnimationFrame(() => { | |
// cancel(); // <-- cancels the inner callback (the outer has already executed) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment