Skip to content

Instantly share code, notes, and snippets.

@AsaoluElijah
Created June 20, 2024 16:39
Show Gist options
  • Save AsaoluElijah/7acad2660a54364ccdf8b700ddba482b to your computer and use it in GitHub Desktop.
Save AsaoluElijah/7acad2660a54364ccdf8b700ddba482b to your computer and use it in GitHub Desktop.
Implementing Throttling with JavaScript
class Throttler {
constructor(maxRequests, period) {
this.maxRequests = maxRequests;
this.period = period;
this.requestTimes = [];
}
addTokens() {
const now = Date.now();
this.requestTimes = this.requestTimes.filter(time => now - time < this.period);
}
allowRequest() {
this.addTokens();
if (this.requestTimes.length < this.maxRequests) {
this.requestTimes.push(Date.now());
return true;
}
return false;
}
delayRequest() {
const waitTime = this.timeUntilNextAllowedRequest();
if (waitTime > 0) {
console.log(`Delaying request for ${waitTime}ms`);
return new Promise(resolve => setTimeout(resolve, waitTime));
}
return Promise.resolve();
}
timeUntilNextAllowedRequest() {
if (this.requestTimes.length === 0) {
return 0;
}
const earliestRequestTime = this.requestTimes[0];
const now = Date.now();
return Math.max(0, (earliestRequestTime + this.period) - now);
}
}
/* ================================
USAGE EXAMPLE
===================================
*/
// Initialize throttler
const throttler = new Throttler(10, 60000); // 10 requests per 60 seconds
// Simulate requests using fetch
async function handleRequest() {
if (throttler.allowRequest()) {
console.log("Request allowed");
// Simulate API request
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
} else {
await throttler.delayRequest();
console.log("Request delayed, trying again");
handleRequest();
}
}
// Simulate requests every 2 seconds
for (let i = 1; i <= 20; i++) {
setTimeout(handleRequest, i * 2000); // Simulate a request every 2 seconds
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment