Created
July 27, 2019 01:35
-
-
Save ezekielchentnik/cc95fe1b78c98509479bac0f92b0a23c to your computer and use it in GitHub Desktop.
Request Idle Callback 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
// 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