1. class RequestThrottler {
  2. constructor(queue, delayMs) {
  3. this.queue = queue; // The task queue to throttle
  4. this.delayMs = delayMs; // Delay in milliseconds
  5. this.lastExecutionTime = 0;
  6. this.running = false;
  7. }
  8. async executeTask(task) {
  9. if (this.running) {
  10. // Queue the task if already running
  11. this.queue.push(task);
  12. return;
  13. }
  14. this.running = true;
  15. const now = Date.now();
  16. if (now - this.lastExecutionTime < this.delayMs) {
  17. // Wait if the delay hasn't passed
  18. const waitTime = this.delayMs - (now - this.lastExecutionTime);
  19. await new Promise(resolve => setTimeout(resolve, waitTime));
  20. }
  21. this.lastExecutionTime = Date.now();
  22. try {
  23. await task(); // Execute the task
  24. } catch (error) {
  25. console.error("Task failed:", error); // Log errors
  26. } finally {
  27. this.running = false;
  28. //Process the next task from the queue
  29. if(this.queue.length > 0){
  30. this.executeTask(this.queue.shift());
  31. }
  32. }
  33. }
  34. }
  35. //Example Usage
  36. // const taskQueue = [];
  37. // const throttler = new RequestThrottler(taskQueue, 1000); // Throttle to 1000ms (1 second)
  38. // // Simulate some tasks
  39. // async function task1() {
  40. // console.log("Task 1 executed");
  41. // await new Promise(resolve => setTimeout(resolve, 500));
  42. // }
  43. // async function task2() {
  44. // console.log("Task 2 executed");
  45. // await new Promise(resolve => setTimeout(resolve, 700));
  46. // }
  47. // throttler.executeTask(task1);
  48. // throttler.executeTask(task2);
  49. // throttler.executeTask(task1); //Will be throttled
  50. // throttler.executeTask(task2); //Will be throttled
  51. // throttler.executeTask(task1); //Will be throttled

Add your comment