You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

29 lines
756 B

  1. // Wrapper to call requestIdleCallback() to schedule low-priority work.
  2. // See https://developer.mozilla.org/en-US/docs/Web/API/Background_Tasks_API
  3. // for a good breakdown of the concepts behind this.
  4. import Queue from 'tiny-queue';
  5. const taskQueue = new Queue();
  6. let runningRequestIdleCallback = false;
  7. function runTasks(deadline) {
  8. while (taskQueue.length && deadline.timeRemaining() > 0) {
  9. taskQueue.shift()();
  10. }
  11. if (taskQueue.length) {
  12. requestIdleCallback(runTasks);
  13. } else {
  14. runningRequestIdleCallback = false;
  15. }
  16. }
  17. function scheduleIdleTask(task) {
  18. taskQueue.push(task);
  19. if (!runningRequestIdleCallback) {
  20. runningRequestIdleCallback = true;
  21. requestIdleCallback(runTasks);
  22. }
  23. }
  24. export default scheduleIdleTask;