pinafore/routes/_utils/scheduleIdleTask.js

45 lines
1.2 KiB
JavaScript
Raw Normal View History

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
const liteRIC = cb => setTimeout(() => cb({timeRemaining: () => Infinity})) // eslint-disable-line
function getRIC () {
// we load polyfills asynchronously, so there's a tiny chance this is not defined
return typeof requestIdleCallback !== 'undefined' ? requestIdleCallback : liteRIC
}
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) {
let task = taskQueue.shift()
try {
task()
} catch (e) {
console.error(e)
}
2018-01-31 05:17:01 +00:00
}
if (taskQueue.length) {
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
let rIC = getRIC()
rIC(runTasks)
2018-01-31 05:17:01 +00:00
}
2018-02-09 06:29:29 +00:00
}