class TaskQueue {
constructor() {
this.tasks = [];
this.isRunning = false;
}
addTask(task) {
this.tasks.push(task);
}
start() {
if (this.isRunning) return; // Prevent multiple starts
this.isRunning = true;
this.executeNextTask();
}
executeNextTask() {
if (!this.isRunning) return; // Ensure queue is running
if (this.tasks.length === 0) {
this.isRunning = false;
return; // Queue is empty
}
const task = this.tasks.shift(); // Get the next task
try {
task(); // Execute the task
} catch (error) {
console.error("Task execution error:", error); // Handle errors
} finally {
this.executeNextTask(); // Continue with the next task
}
}
stop() {
this.isRunning = false;
}
}
// Example usage:
// const taskQueue = new TaskQueue();
// taskQueue.addTask(() => console.log("Task 1 executed"));
// taskQueue.addTask(() => console.log("Task 2 executed"));
// taskQueue.start();
Add your comment