idle-until-urgent
Version:
Defer JS work until the browser has a chance to breathe
12 lines (10 loc) • 337 B
JavaScript
const root = typeof window != 'undefined' ? window : global
module.exports = (fn, timeoutFallbackMs = 1000) => {
if ('requestIdleCallback' in root) {
const handle = requestIdleCallback(fn)
return () => cancelIdleCallback(handle)
} else {
const handle = setTimeout(fn, timeoutFallbackMs)
return () => clearTimeout(handle)
}
}