class LeakyBucket { //高并發情況下的漏桶算法
constructor(capacity, leakRate) { // 創建一個容量為capacity,每秒漏水量為leakRate的漏桶
this.capacity = capacity;
this.leakRate = leakRate;
this.water = 0;
this.lastLeakTime = Date.now();
}
allow(waterAmount) {
const currentTime = Date.now();
const leakAmount = (currentTime - this.lastLeakTime) / 1000 * this.leakRate;
this.water = Math.max(0, this.water - leakAmount);
this.lastLeakTime = currentTime;
if (this.water + waterAmount > this.capacity) {
return false; // bucket overflow
} else {
this.water += waterAmount;
return true;
}
}
}
const bucket = new LeakyBucket(5, 1);
document.getElementById("asdf").onclick = function () {
if(bucket.allow(1)){
console.log("走請求");
}else{
console.log("歇一會");
}
}