Created
August 15, 2019 09:30
-
-
Save lunelson/84611d82a03f49333a5f8fd070aa3269 to your computer and use it in GitHub Desktop.
Pattern for syncing rapid events to the AF loop
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 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