2018-01-31 05:17:01 +00:00
|
|
|
// Wrapper to call requestIdleCallback() to schedule low-priority work.
|
|
|
|
// See https://developer.mozilla.org/en-US/docs/Web/API/Background_Tasks_API
|
|
|
|
// for a good breakdown of the concepts behind this.
|
|
|
|
|
|
|
|
import Queue from 'tiny-queue'
|
2018-02-25 19:20:40 +00:00
|
|
|
import { mark, stop } from './marks'
|
2018-01-31 05:17:01 +00:00
|
|
|
|
|
|
|
const taskQueue = new Queue()
|
|
|
|
let runningRequestIdleCallback = false
|
|
|
|
|
2018-04-21 08:33:36 +01:00
|
|
|
const liteRIC = cb => setTimeout(() => cb({timeRemaining: () => Infinity})) // eslint-disable-line
|
|
|
|
|
2018-04-19 18:35:34 +01:00
|
|
|
function getRIC () {
|
|
|
|
// we load polyfills asynchronously, so there's a tiny chance this is not defined
|
2018-04-21 08:33:36 +01:00
|
|
|
return typeof requestIdleCallback !== 'undefined' ? requestIdleCallback : liteRIC
|
2018-04-19 18:35:34 +01:00
|
|
|
}
|
|
|
|
|
2018-02-09 06:29:29 +00:00
|
|
|
function runTasks (deadline) {
|
2018-02-25 19:20:40 +00:00
|
|
|
mark('scheduleIdleTask:runTasks()')
|
2018-01-31 05:17:01 +00:00
|
|
|
while (taskQueue.length && deadline.timeRemaining() > 0) {
|
2018-04-21 08:33:36 +01:00
|
|
|
let task = taskQueue.shift()
|
|
|
|
try {
|
|
|
|
task()
|
|
|
|
} catch (e) {
|
|
|
|
console.error(e)
|
|
|
|
}
|
2018-01-31 05:17:01 +00:00
|
|
|
}
|
|
|
|
if (taskQueue.length) {
|
2018-04-19 18:35:34 +01:00
|
|
|
let rIC = getRIC()
|
|
|
|
rIC(runTasks)
|
2018-01-31 05:17:01 +00:00
|
|
|
} else {
|
|
|
|
runningRequestIdleCallback = false
|
|
|
|
}
|
2018-02-25 19:20:40 +00:00
|
|
|
stop('scheduleIdleTask:runTasks()')
|
2018-01-31 05:17:01 +00:00
|
|
|
}
|
|
|
|
|
2018-02-09 06:29:29 +00:00
|
|
|
export function scheduleIdleTask (task) {
|
2018-01-31 05:17:01 +00:00
|
|
|
taskQueue.push(task)
|
|
|
|
if (!runningRequestIdleCallback) {
|
|
|
|
runningRequestIdleCallback = true
|
2018-04-19 18:35:34 +01:00
|
|
|
let rIC = getRIC()
|
|
|
|
rIC(runTasks)
|
2018-01-31 05:17:01 +00:00
|
|
|
}
|
2018-02-09 06:29:29 +00:00
|
|
|
}
|