Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Pattern for syncing rapid events to the AF loop
function syncToFrames(el, eventName, frameCB, postFrameCB) {
let active = false;
function deactivate() { active = false; }
function activate() {
if (!active) {
setTimeout(onPostFrame);
requestAnimationFrame(onFrame);
}
else { clearTimeout(active); }
active = setTimeout(deactivate, 100); // minimum event frequency is 100ms; could be shorter
}
function onPostFrame() { postFrameCB(performance.now()); }
function onFrame(timestamp) {
frameCB(timestamp);
if (active) {
setTimeout(onPostFrame);
requestAnimationFrame(onFrame);
}
}
el.addEventListener(eventName, activate);
return activate; // so handler can be removed if desired
}
// USAGE example:
const scrollHandler = syncToFrames(window, 'scroll', timestamp => {
console.log(`acting on animationFrame at ${timestamp}`)
}, timestamp => {
console.log(`acting on postAnimationFrame at ${timestamp}`)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.