Pinafore-Web-Client-Frontend/routes/_utils/scheduleIdleTask.js

38 lines
1.0 KiB
JavaScript
Raw Normal View History

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
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) {
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
let rIC = getRIC()
rIC(runTasks)
2018-01-31 06:17:01 +01:00
}
2018-02-09 07:29:29 +01:00
}