Created
June 20, 2024 16:39
-
-
Save AsaoluElijah/7acad2660a54364ccdf8b700ddba482b to your computer and use it in GitHub Desktop.
Implementing Throttling with JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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