Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Wrapper around requestIdleCallback to wait for a minimum work budget
/**
* Delays calling the given function until the browser is notifying us
* about a certain minimum budget or the timeout is reached.
* @param {!Window} win
* @param {number} startTime When we started waiting for idle.
* @param {number} minimumTimeRemaining Minimum number of millis idle
* budget for callback to fire.
* @param {number} timeout in millis for callback to fire.
* @param {function()} fn Callback.
*/
export function onIdle(win, startTime, minimumTimeRemaining, timeout, fn) {
win.requestIdleCallback(info => {
if (info.timeRemaining() < minimumTimeRemaining) {
const now = Date.now();
const remainingTimeout = timeout - (now - startTime);
if (remainingTimeout <= 0 || info.didTimeout) {
fn();
} else {
onIdle(win, now, minimumTimeRemaining, remainingTimeout, fn);
}
} else {
fn();
}
}, {
timeout: timeout,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.