class RateLimiter {
constructor(limit, interval) {
this.limit = limit;
this.interval = interval;
this.queue = [];
this.timer = null;
}
/**
* Attempts to execute a script if within rate limits.
* @param {function} script The script to execute.
* @returns {boolean} True if executed, false if rate limited.
*/
execute(script) {
if (this.queue.length >= this.limit) {
return false; // Rate limited
}
this.queue.push(script);
this.processQueue();
return true;
}
/**
* Processes the queue of scripts.
*/
processQueue() {
if (this.timer) {
return; // Already running
}
this.timer = setTimeout(() => {
while (this.queue.length > 0) {
const script = this.queue.shift();
try {
script();
} catch (error) {
console.error("Script execution error:", error);
}
}
this.timer = null;
}, this.interval);
}
}
// Example Usage: (for sandbox)
const rateLimiter = new RateLimiter(5, 1000); // Limit 5 scripts per 1000ms (1 second)
// Define some sample scripts
const script1 = () => { console.log("Script 1 executed"); };
const script2 = () => { console.log("Script 2 executed"); };
const script3 = () => { console.log("Script 3 executed"); };
const script4 = () => { console.log("Script 4 executed"); };
const script5 = () => { console.log("Script 5 executed"); };
const script6 = () => { console.log("Script 6 executed"); }; //will be rate limited.
// Test execution
console.log("Executing script 1...");
rateLimiter.execute(script1);
console.log("Executing script 2...");
rateLimiter.execute(script2);
console.log("Executing script 3...");
rateLimiter.execute(script3);
console.log("Executing script 4...");
rateLimiter.execute(script4);
console.log("Executing script 5...");
rateLimiter.execute(script5);
console.log("Executing script 6..."); // rate limited.
// You can add more scripts as needed.
Add your comment