Skip to content

Instantly share code, notes, and snippets.

@lunelson
Created August 15, 2019 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lunelson/84611d82a03f49333a5f8fd070aa3269 to your computer and use it in GitHub Desktop.
Save lunelson/84611d82a03f49333a5f8fd070aa3269 to your computer and use it in GitHub Desktop.
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