2018-01-31 06:17:01 +01: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 20:20:40 +01:00
|
|
|
import { mark, stop } from './marks'
|
2018-01-31 06:17:01 +01:00
|
|
|
|
|
|
|
const taskQueue = new Queue()
|
|
|
|
let runningRequestIdleCallback = false
|
|
|
|
|
2018-04-19 19:35:34 +02:00
|
|
|
function getRIC () {
|
|
|
|
// we load polyfills asynchronously, so there's a tiny chance this is not defined
|
|
|
|
return typeof requestIdleCallback !== 'undefined' ? requestIdleCallback : setTimeout
|
|
|
|
}
|
|
|
|
|
2018-02-09 07:29:29 +01:00
|
|
|
function runTasks (deadline) {
|
2018-02-25 20:20:40 +01:00
|
|
|
mark('scheduleIdleTask:runTasks()')
|
2018-01-31 06:17:01 +01:00
|
|
|
while (taskQueue.length && deadline.timeRemaining() > 0) {
|
|
|
|
taskQueue.shift()()
|
|
|
|
}
|
|
|
|
if (taskQueue.length) {
|
2018-04-19 19:35:34 +02:00
|
|
|
let rIC = getRIC()
|
|
|
|
rIC(runTasks)
|
2018-01-31 06:17:01 +01:00
|
|
|
} else {
|
|
|
|
runningRequestIdleCallback = false
|
|
|
|
}
|
2018-02-25 20:20:40 +01:00
|
|
|
stop('scheduleIdleTask:runTasks()')
|
2018-01-31 06:17:01 +01:00
|
|
|
}
|
|
|
|
|
2018-02-09 07:29:29 +01:00
|
|
|
export function scheduleIdleTask (task) {
|
2018-01-31 06:17:01 +01:00
|
|
|
taskQueue.push(task)
|
|
|
|
if (!runningRequestIdleCallback) {
|
|
|
|
runningRequestIdleCallback = true
|
2018-04-19 19:35:34 +02:00
|
|
|
let rIC = getRIC()
|
|
|
|
rIC(runTasks)
|
2018-01-31 06:17:01 +01:00
|
|
|
}
|
2018-02-09 07:29:29 +01:00
|
|
|
}
|