1. class RateLimiter {
  2. constructor(limit, interval) {
  3. this.limit = limit;
  4. this.interval = interval;
  5. this.queue = [];
  6. this.timer = null;
  7. }
  8. /**
  9. * Attempts to execute a script if within rate limits.
  10. * @param {function} script The script to execute.
  11. * @returns {boolean} True if executed, false if rate limited.
  12. */
  13. execute(script) {
  14. if (this.queue.length >= this.limit) {
  15. return false; // Rate limited
  16. }
  17. this.queue.push(script);
  18. this.processQueue();
  19. return true;
  20. }
  21. /**
  22. * Processes the queue of scripts.
  23. */
  24. processQueue() {
  25. if (this.timer) {
  26. return; // Already running
  27. }
  28. this.timer = setTimeout(() => {
  29. while (this.queue.length > 0) {
  30. const script = this.queue.shift();
  31. try {
  32. script();
  33. } catch (error) {
  34. console.error("Script execution error:", error);
  35. }
  36. }
  37. this.timer = null;
  38. }, this.interval);
  39. }
  40. }
  41. // Example Usage: (for sandbox)
  42. const rateLimiter = new RateLimiter(5, 1000); // Limit 5 scripts per 1000ms (1 second)
  43. // Define some sample scripts
  44. const script1 = () => { console.log("Script 1 executed"); };
  45. const script2 = () => { console.log("Script 2 executed"); };
  46. const script3 = () => { console.log("Script 3 executed"); };
  47. const script4 = () => { console.log("Script 4 executed"); };
  48. const script5 = () => { console.log("Script 5 executed"); };
  49. const script6 = () => { console.log("Script 6 executed"); }; //will be rate limited.
  50. // Test execution
  51. console.log("Executing script 1...");
  52. rateLimiter.execute(script1);
  53. console.log("Executing script 2...");
  54. rateLimiter.execute(script2);
  55. console.log("Executing script 3...");
  56. rateLimiter.execute(script3);
  57. console.log("Executing script 4...");
  58. rateLimiter.execute(script4);
  59. console.log("Executing script 5...");
  60. rateLimiter.execute(script5);
  61. console.log("Executing script 6..."); // rate limited.
  62. // You can add more scripts as needed.

Add your comment