Skip to content

Instantly share code, notes, and snippets.

@pomber
Last active Mar 15, 2018
Embed
What would you like to do?
Using requestIdleFrame to schedule tasks
const ENOUGH_TIME = 1; // milliseconds
let workQueue = [];
let nextUnitOfWork = null;
function schedule(task) {
workQueue.push(task);
requestIdleCallback(performWork);
}
function performWork(deadline) {
if (!nextUnitOfWork) {
nextUnitOfWork = workQueue.shift();
}
while (nextUnitOfWork && deadline.timeRemaining() > ENOUGH_TIME) {
nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
}
if (nextUnitOfWork || workQueue.length > 0) {
requestIdleCallback(performWork);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment