about summary refs log tree commit diff
path: root/app/javascript/flavours/glitch/util/schedule_idle_task.js
blob: b04d4a8eefa3b7d22c55b088f2e724714f7f4715 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 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';

const taskQueue = new Queue();
let runningRequestIdleCallback = false;

function runTasks(deadline) {
  while (taskQueue.length && deadline.timeRemaining() > 0) {
    taskQueue.shift()();
  }
  if (taskQueue.length) {
    requestIdleCallback(runTasks);
  } else {
    runningRequestIdleCallback = false;
  }
}

function scheduleIdleTask(task) {
  taskQueue.push(task);
  if (!runningRequestIdleCallback) {
    runningRequestIdleCallback = true;
    requestIdleCallback(runTasks);
  }
}

export default scheduleIdleTask;