Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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