1. class TextBlock {
  2. constructor(id, text, delay) {
  3. this.id = id;
  4. this.text = text;
  5. this.delay = delay;
  6. this.timer = null;
  7. }
  8. async display() {
  9. // Display the text
  10. console.log(`Displaying block ${this.id}: ${this.text}`);
  11. // Set a timer to hide the block after the delay
  12. this.timer = setTimeout(() => {
  13. this.hide();
  14. }, this.delay);
  15. }
  16. hide() {
  17. // Remove the block from the display
  18. console.log(`Hiding block ${this.id}`);
  19. clearTimeout(this.timer); // Clear the timer
  20. this.timer = null;
  21. }
  22. }
  23. class TextBlockManager {
  24. constructor(rateLimit = 1000) {
  25. this.textBlocks = [];
  26. this.rateLimit = rateLimit;
  27. this.nextId = 1;
  28. }
  29. addTextBlock(text, delay) {
  30. const newBlock = new TextBlock(this.nextId++, text, delay);
  31. this.textBlocks.push(newBlock);
  32. return newBlock;
  33. }
  34. async run() {
  35. for (const block of this.textBlocks) {
  36. await new Promise(resolve => setTimeout(resolve, block.delay)); //Respect delay
  37. block.display();
  38. }
  39. }
  40. }
  41. // Example Usage:
  42. const manager = new TextBlockManager(500); // Rate limit of 500ms
  43. const block1 = manager.addTextBlock("First block", 1000);
  44. const block2 = manager.addTextBlock("Second block", 500);
  45. const block3 = manager.addTextBlock("Third block", 750);
  46. const block4 = manager.addTextBlock("Fourth block", 1200);
  47. const block5 = manager.addTextBlock("Fifth block", 600);
  48. manager.run();

Add your comment