Skip to content

IdleQueue

Eugene Lazutkin edited this page Feb 25, 2026 · 7 revisions

Description

IdleQueue is a specialized queue that extends ListQueue and uses the browser's requestIdleCallback() API to schedule tasks during idle periods. This makes it ideal for executing background tasks that should not interfere with critical user interactions or animations.

Usually IdleQueue is used for non-urgent background tasks that can be deferred until the browser is idle.

Key features

  • Idle-Time Execution: Tasks are executed during browser idle periods using requestIdleCallback().
  • Timeout Handling: Configurable timeout batch size for handling cases when the browser is continuously busy.
  • Efficient Resource Usage: Optimizes CPU usage by running tasks only when the browser is not busy with higher-priority work.

Technical specifications

IdleQueue is available as a named export. The default export is idleQueue, a global instance of IdleQueue.

const queue = new IdleQueue(paused, timeoutBatchInMs, options);

// idleQueue is a global instance of IdleQueue:
// const idleQueue = new IdleQueue();
void idleQueue;

// Enqueue a function using the global queue:
const task = defer(fn);
// the same as:
// const task = idleQueue.enqueue(fn);

Constructor parameters

  • paused: A boolean indicating whether the queue should start in a paused state. Default is false.
  • timeoutBatchInMs: An optional number specifying the maximum time (in milliseconds) to spend executing tasks when the browser is busy and the idle callback times out. If undefined, all tasks are run in a single batch.
  • options: An optional object containing options for requestIdleCallback(), such as a timeout.

Instance properties

  • paused: A boolean indicating whether the queue is currently paused (inherited from MicroTaskQueue).
  • timeoutBatch: The timeout batch size in milliseconds for running tasks. Used only when deadline.didTimeout is true.
  • options: The options passed to requestIdleCallback().
  • stopQueue: A function or null that is used to stop the queue when paused. It's set by the startQueue method. This property is used internally by pause() and resume().

Instance getters

  • isEmpty: A boolean indicating whether the queue is empty (inherited from ListQueue).

Instance methods

  • pause(): Pauses the queue, preventing tasks from being executed. If the queue is running, it calls the stopQueue function to halt execution. Returns the queue instance.
  • resume(): Resumes the queue, allowing tasks to be executed again. If the queue is not empty, it calls the startQueue method to begin execution. Returns the queue instance.
  • enqueue(fn): Adds a new task to the queue. Returns the task instance.
  • dequeue(task): Removes a specified task from the queue. Returns the queue instance.
    • task.cancel() is called when the task is removed from the queue.
  • schedule(fn): Similar to enqueue(), but returns a task instance with a non-null promise property that resolves when the task is executed.
    • When the task is executed, the promise is resolved with the return value of fn(), or rejected with the error thrown by fn(), if any.
  • clear(): Clears all tasks from the queue. Returns the queue instance.
    • task.cancel() is called for all tasks in the queue.
  • startQueue(): Starts the queue by calling requestIdleCallback() and returns a function that cancels the idle callback.

fn is a function that will be executed when the task is scheduled:

  • It will be called with an object containing the following properties:
    • deadline: An IdleDeadline object provided by requestIdleCallback().
    • task: The MicroTask instance representing the current task.
    • queue: The IdleQueue instance.
  • It will be called in the context of the task object.
  • Its return value will be ignored by enqueue(), but it can be used by schedule() to resolve the task's promise.

task is an instance of the MicroTask class. It is created by the enqueue() method when a new task is added to the queue.

Additional exports

  • idleQueue: A global instance of IdleQueue.
  • defer(fn): A function that enqueues a function using the global queue.

Usage instructions

To use the IdleQueue class, import it into your project and create an instance:

import {IdleQueue, idleQueue, defer} from 'time-queues/IdleQueue.js';

// Use the default global queue (preferred)
defer(() => console.log('This task will run during browser idle time'));

// Or create your own queue with custom settings
const customQueue = new IdleQueue(false, 50, {timeout: 2000});
customQueue.enqueue(({deadline, task, queue}) => {
  console.log('Custom queue task with remaining time:', deadline.timeRemaining());
});

// Control the queue
customQueue.pause(); // Pause the queue
customQueue.resume(); // Resume the queue
customQueue.clear(); // Clear all tasks

Troubleshooting

  • Tasks Not Executing: Ensure that the browser supports requestIdleCallback(). If not, consider using a polyfill or an alternative approach.
  • Tasks Taking Too Long: If tasks are taking too long to execute, consider breaking them into smaller chunks or adjusting the timeoutBatchInMs parameter.
  • High Priority Tasks Delayed: Remember that IdleQueue is designed for background tasks. For high-priority tasks that need immediate execution, consider using a different queue type.

See Also

Clone this wiki locally