Skip to content

Instantly share code, notes, and snippets.

@richardscarrott
Last active October 18, 2022 10:19
Show Gist options
  • Save richardscarrott/5d8eee84481a73688588ba584f9c2ff8 to your computer and use it in GitHub Desktop.
Save richardscarrott/5d8eee84481a73688588ba584f9c2ff8 to your computer and use it in GitHub Desktop.
Utility to enqueue + cancel callback for *next* animation frame (Double rAF)
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