1. class TaskQueue {
  2. constructor() {
  3. this.tasks = [];
  4. this.isRunning = false;
  5. }
  6. addTask(task) {
  7. this.tasks.push(task);
  8. }
  9. start() {
  10. if (this.isRunning) return; // Prevent multiple starts
  11. this.isRunning = true;
  12. this.executeNextTask();
  13. }
  14. executeNextTask() {
  15. if (!this.isRunning) return; // Ensure queue is running
  16. if (this.tasks.length === 0) {
  17. this.isRunning = false;
  18. return; // Queue is empty
  19. }
  20. const task = this.tasks.shift(); // Get the next task
  21. try {
  22. task(); // Execute the task
  23. } catch (error) {
  24. console.error("Task execution error:", error); // Handle errors
  25. } finally {
  26. this.executeNextTask(); // Continue with the next task
  27. }
  28. }
  29. stop() {
  30. this.isRunning = false;
  31. }
  32. }
  33. // Example usage:
  34. // const taskQueue = new TaskQueue();
  35. // taskQueue.addTask(() => console.log("Task 1 executed"));
  36. // taskQueue.addTask(() => console.log("Task 2 executed"));
  37. // taskQueue.start();

Add your comment