Created
June 18, 2019 19:59
-
-
Save ccnokes/094e8e447c58ed90a55e0488378222fa to your computer and use it in GitHub Desktop.
requestAnimationFrame scheduler
This file contains 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
/** | |
* 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