Last active
March 15, 2018 19:03
-
-
Save pomber/cf0a9e31ec3834e6af0a2c1992c1180d to your computer and use it in GitHub Desktop.
Using requestIdleFrame to schedule tasks
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
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