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-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) {
|
|
|
|
taskQueue.shift()()
|
|
|
|
}
|
|
|
|
if (taskQueue.length) {
|
|
|
|
requestIdleCallback(runTasks)
|
|
|
|
} 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
|
|
|
|
requestIdleCallback(runTasks)
|
|
|
|
}
|
2018-02-09 06:29:29 +00:00
|
|
|
}
|