Skip to content

Instantly share code, notes, and snippets.

@ezekielchentnik
Created July 27, 2019 01:35
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 ezekielchentnik/cc95fe1b78c98509479bac0f92b0a23c to your computer and use it in GitHub Desktop.
Save ezekielchentnik/cc95fe1b78c98509479bac0f92b0a23c to your computer and use it in GitHub Desktop.
Request Idle Callback Scheduler
// Wait at most one frame before processing events.
const BUDGET = 16.7;
let isRequestIdleCallbackScheduled = false;
const scheduleWork = () => {
// Only schedule the rIC if one has not already been set.
if (isRequestIdleCallbackScheduled) {
return;
}
isRequestIdleCallbackScheduled = true;
requestIdleCallback(processWork, { timeout: BUDGET });
};
const processWork = deadline => {
// If there is no deadline, just run as long as necessary.
if (typeof deadline === "undefined") {
deadline = {
timeRemaining: function() {
return Number.MAX_VALUE;
}
};
}
let conditionForWork = true; // implement condition based on actual work
// Go for as long as there is time remaining and work to do.
while (deadline.timeRemaining() > 0 && conditionForWork) {
// do work here
// optional: wait for the next requestAnimationFrame callback
// to do something with results of work.
scheduleRAFIfNeeded();
}
let conditionForMoreWork = true; // implement condition for more work
// Check if there is more work
if (conditionForMoreWork) {
scheduleWork();
}
};
const onNextFrame = () => {
// raf callback
};
let isScheduled = false;
const scheduleRAFIfNeeded = () => {
if (isScheduled) {
return;
}
isScheduled = true;
requestAnimationFrame(onNextFrame);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment