class RequestThrottler {
constructor(queue, delayMs) {
this.queue = queue; // The task queue to throttle
this.delayMs = delayMs; // Delay in milliseconds
this.lastExecutionTime = 0;
this.running = false;
}
async executeTask(task) {
if (this.running) {
// Queue the task if already running
this.queue.push(task);
return;
}
this.running = true;
const now = Date.now();
if (now - this.lastExecutionTime < this.delayMs) {
// Wait if the delay hasn't passed
const waitTime = this.delayMs - (now - this.lastExecutionTime);
await new Promise(resolve => setTimeout(resolve, waitTime));
}
this.lastExecutionTime = Date.now();
try {
await task(); // Execute the task
} catch (error) {
console.error("Task failed:", error); // Log errors
} finally {
this.running = false;
//Process the next task from the queue
if(this.queue.length > 0){
this.executeTask(this.queue.shift());
}
}
}
}
//Example Usage
// const taskQueue = [];
// const throttler = new RequestThrottler(taskQueue, 1000); // Throttle to 1000ms (1 second)
// // Simulate some tasks
// async function task1() {
// console.log("Task 1 executed");
// await new Promise(resolve => setTimeout(resolve, 500));
// }
// async function task2() {
// console.log("Task 2 executed");
// await new Promise(resolve => setTimeout(resolve, 700));
// }
// throttler.executeTask(task1);
// throttler.executeTask(task2);
// throttler.executeTask(task1); //Will be throttled
// throttler.executeTask(task2); //Will be throttled
// throttler.executeTask(task1); //Will be throttled
Add your comment