Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Created June 18, 2019 19:59
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 ccnokes/094e8e447c58ed90a55e0488378222fa to your computer and use it in GitHub Desktop.
Save ccnokes/094e8e447c58ed90a55e0488378222fa to your computer and use it in GitHub Desktop.
requestAnimationFrame scheduler
/**
* A function for batching RAFs together
*/
export default function RAFScheduler() {
let queue = [];
let rafId;
let scheduled = false;
const DURATION = 10;
return function scheduleRaf(cb: () => void) {
queue.push(cb);
let schedule = () => {
scheduled = true;
rafId = requestAnimationFrame(timestamp => {
let targetEnd = performance.now() + DURATION;
while(queue.length > 0 && performance.now() <= targetEnd) {
let task = queue.shift();
task();
}
if (queue.length > 0) {
schedule();
} else {
scheduled = false;
}
});
};
if (!scheduled) {
schedule();
}
return function cancelScheduledRaf() {
let index = queue.indexOf(cb);
if (index > -1) {
queue.splice(index, 1);
}
if (queue.length === 0) {
cancelAnimationFrame(rafId);
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment