-
-
Notifications
You must be signed in to change notification settings - Fork 0
MicroTaskQueue
MicroTaskQueue is a base class for queues of microtasks. It provides a framework for managing and executing tasks in a controlled manner, allowing for the scheduling of tasks and providing methods to pause and resume task execution.
Usually MicroTaskQueue is used as a base class for other classes that implement specific task processing logic.
- Task Management: Provides methods to enqueue, dequeue, pause, and resume tasks.
- Flexible Implementation: Should be extended to create custom behavior for task processing.
MicroTaskQueue is available as a named and default export.
const queue = new MicroTaskQueue(paused);-
paused: A boolean indicating whether the queue should start in a paused state.
-
paused: A boolean indicating whether the queue is currently paused.
-
isEmpty: A boolean indicating whether the queue is empty.
-
pause(): Pauses the queue, preventing tasks from being executed. Returns the queue instance. -
resume(): Resumes the queue, allowing tasks to be executed again. Returns the queue instance. -
enqueue(fn): Adds a new task to the queue, wrapping the provided function in aMicroTaskinstance. 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, ...args): 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. -
argsis there to accommodate any additional arguments that will be passed toenqueue(). They can be used in subclasses to customize the task's behavior.
- 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.
-
fn is a function that will be executed when the task is scheduled. It will be called with queue-specific arguments, and 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() or schedule() methods when a new task is added to the queue.
To use the MicroTaskQueue class, import it into your project and create an instance:
import MicroTaskQueue from 'time-queues/MicroTaskQueue.js';
const queue = new MicroTaskQueue();
queue.pause();
queue.enqueue(() => console.log('Task executed'));
queue.resume();
queue.clear();- Function Not Executing: Ensure that the methods are being called correctly and that the queue is not paused when tasks are expected to run.
- Task Management Issues: If tasks are not being managed as expected, verify the implementation of the queue methods.