Skip to content

Instantly share code, notes, and snippets.

@cramforce
Created December 7, 2016 16:49
Show Gist options
  • Save cramforce/ea2dbca61d2f4800c57566586cd2f2e9 to your computer and use it in GitHub Desktop.
Save cramforce/ea2dbca61d2f4800c57566586cd2f2e9 to your computer and use it in GitHub Desktop.
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