-
-
Notifications
You must be signed in to change notification settings - Fork 0
IdleQueue
Eugene Lazutkin edited this page Feb 25, 2026
·
7 revisions
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.
-
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.
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);-
paused: A boolean indicating whether the queue should start in a paused state. Default isfalse. -
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 forrequestIdleCallback(), such as a timeout.
-
paused: A boolean indicating whether the queue is currently paused (inherited fromMicroTaskQueue). -
timeoutBatch: The timeout batch size in milliseconds for running tasks. Used only whendeadline.didTimeoutistrue. -
options: The options passed torequestIdleCallback(). -
stopQueue: A function ornullthat is used to stop the queue when paused. It's set by thestartQueuemethod. This property is used internally bypause()andresume().
-
isEmpty: A boolean indicating whether the queue is empty (inherited fromListQueue).
-
pause(): Pauses the queue, preventing tasks from being executed. If the queue is running, it calls thestopQueuefunction 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 thestartQueuemethod 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 toenqueue(), but returns a task instance with a non-nullpromiseproperty 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 byfn(), if any.
- When the task is executed, the promise is resolved with the return value of
-
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 callingrequestIdleCallback()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: AnIdleDeadlineobject provided byrequestIdleCallback(). -
task: TheMicroTaskinstance representing the current task. -
queue: TheIdleQueueinstance.
-
- It will be called in the context of the task object.
- Its return value will be ignored by
enqueue(), but it can be used byschedule()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.
-
idleQueue: A global instance ofIdleQueue. -
defer(fn): A function that enqueues a function using the global queue.
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-
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
timeoutBatchInMsparameter. -
High Priority Tasks Delayed: Remember that
IdleQueueis designed for background tasks. For high-priority tasks that need immediate execution, consider using a different queue type.
- ListQueue - Parent class
- FrameQueue - Browser animation frame queue
- Scheduler - Time-based scheduling