Created
December 7, 2016 16:49
-
-
Save cramforce/ea2dbca61d2f4800c57566586cd2f2e9 to your computer and use it in GitHub Desktop.
Wrapper around requestIdleCallback to wait for a minimum work budget
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
/** | |
* 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