class InputThrottler {
constructor(limit = 5, interval = 1000) {
this.limit = limit; // Maximum number of requests allowed within the interval
this.interval = interval; // Time interval in milliseconds
this.queue = []; // Queue to store pending requests
this.running = false; // Flag to indicate if the throttler is running
this.lastExecutionTime = 0; // Timestamp of the last execution
}
/**
* Checks if a request is allowed based on the throttling rules.
* @param {function} requestFunction - The function to be throttled.
* @param {...any} args - Arguments to pass to the request function.
* @returns {boolean} - True if the request is allowed, false otherwise.
*/
isThrottled(requestFunction, ...args) {
if (!this.running) {
this.run();
}
// Check if the queue is full
if (this.queue.length >= this.limit) {
return false;
}
// Add the request to the queue
this.queue.push({ function: requestFunction, args });
return true;
}
/**
* Executes the pending requests in the queue.
*/
async run() {
if (this.running) {
return; // Prevent concurrent runs
}
this.running = true;
const now = Date.now();
// Clear the queue
this.queue = [];
for (let i = 0; i < this.queue.length; i++) {
const { function: requestFunction, args } = this.queue[i];
try {
await requestFunction(...args);
} catch (error) {
console.error("Throttled request failed:", error);
}
}
this.lastExecutionTime = now;
this.running = false;
// Schedule the next execution
setTimeout(() => {
this.run();
}, this.interval);
}
/**
* Sets the throttler to dry-run mode. Requests are logged but not executed.
* @returns {boolean} - true if dry-run mode is enabled.
*/
setDryRunMode(dryRun = true) {
this.dryRun = dryRun;
}
/**
* Returns the dry run status.
* @returns {boolean} - dryRun status.
*/
getDryRunMode() {
return this.dryRun;
}
}
// Example usage:
// const throttler = new InputThrottler(3, 1000); // Limit 3 requests per 1 second
// async function myRequest(data) {
// console.log("Request executed with data:", data);
// // Simulate an asynchronous operation
// await new Promise(resolve => setTimeout(resolve, 200));
// }
// for (let i = 0; i < 10; i++) {
// if (throttler.isThrottled(myRequest, `Data ${i}`)) {
// console.log(`Request ${i} allowed`);
// } else {
// console.log(`Request ${i} throttled`);
// }
// }
// throttler.setDryRunMode(true); //Enable dry run mode
// for (let i = 0; i < 10; i++) {
// if (throttler.isThrottled(myRequest, `Data ${i}`)) {
// console.log(`Request ${i} allowed`);
// } else {
// console.log(`Request ${i} throttled`);
// }
// }
Add your comment