Task Queue
TaskQueue processes queued items in batches of batchSize, waiting batchDelay milliseconds before each batch. Items in a batch are processed one at a time, and an optional getPriority keeps higher-priority items at the front of the queue.
A batchDelay of 0 runs each batch in a microtask rather than a timer. A browser clamps a setTimeout(0) scheduled from inside a timer callback to 4ms once the nesting passes five levels, so a one-item batch whose processItem settles in the same task would otherwise pay 4ms an item.
API
typescript
// Task queue options
export type TaskQueueOptions<Item> = {
batchSize: number;
batchDelay: number;
processItem: (item: Item) => unknown;
getPriority?: (item: Item) => number;
};
// Task queue implementation
export declare class TaskQueue<Item> {
constructor(options: TaskQueueOptions<Item>);
push(item: Item): void;
remove(item: Item): void;
subscribe(subscriber: (item: Item) => void): () => void;
process(): void;
stop(): void;
start(): void;
clear(): void;
}Example
typescript
import { TaskQueue } from '@welshman/lib';
// Create a task queue that processes 3 items at a time
const queue = new TaskQueue({
batchSize: 3,
batchDelay: 0,
processItem: async (message: string) => {
console.log('Processing:', message);
// Simulate async work
await new Promise(resolve => setTimeout(resolve, 100));
}
});
// Add items to the queue
queue.push('Message 1');
queue.push('Message 2');
queue.push('Message 3');
queue.push('Message 4');
// Items will be processed in batches of 3
// Output: "Processing: Message 1", "Processing: Message 2", "Processing: Message 3"
// Then: "Processing: Message 4"