Skip to content

Instantly share code, notes, and snippets.

@karenpeng
Last active January 29, 2016 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karenpeng/16c533dbd078cad7b177 to your computer and use it in GitHub Desktop.
Save karenpeng/16c533dbd078cad7b177 to your computer and use it in GitHub Desktop.
// 假设类中有一个方法,给定时间范围和最大次数,假设在给定时间范围内,test()被用的次数超过最大次数,那么超过的次数无效,并且返回错误,如果没有超过的话,就可以继续调用.
// 例子
// 方法, 范围五秒, 次数三次,
// ----------
// 运行:
// 方法
// 睡1秒
// 方法
// 睡1秒
// 方法
// 睡一秒
// 方法
// 睡一秒
// 方法
// ----------
// 输出
// 可以
// 可以
// 可以
// 不可以
// 不可以
// 题目理解完了,你的思路是什么
//又忘了先讲思路。。。打脸
//closure里面有一个起始时间
//每次被call会 check现在时间跟起始时间的距离
//同时会counter计算被call 了几次
//如果counter > times && 时间距离<duration return false
//else return true
//如果时间距离超过duration, counter重新设为0
//1. no window
function rateLimit(duration, times){
var startTime = Date.now()
var count = 0
return function(){
var _now = Date.now()
if(_now - startTime >= duration) count = 0
if(count < times){
console.log(true)
}else{
console.log(false)
}
count ++
}
}
var test = rateLimit(5000, 3)
for(var i = 0; i < 6; i++){
(function(i){
setTimeout(function(){
test();
}, i * 1000)})(i)
}
//output => true, true, true, false, false, false, true
//2. has window, but there's a timer interval running all the time
function rateLimit(duration, times){
var count = 0
setInterval(function(){
count = 0
}, duration);
return function(){
if(count < times){
console.log(true)
}else{
console.log(false)
}
count ++
}
}
var test = rateLimit(5000, 3);
setTimeout(function(){
test()
}, 800);
setTimeout(function(){
test()
}, 1800);
setTimeout(function(){
test()
}, 3000);
setTimeout(function(){
test()
}, 3600);
setTimeout(function(){
test()
}, 5001);
setTimeout(function(){
test()
}, 5003);
setTimeout(function(){
test()
}, 5004);
setTimeout(function(){
test()
}, 5005);
//output => true, true, true, false, true, true, true, false
//3. no more interval timer :)
function rateLimit(duration, times){
var startTime = Date.now()
var count = 0
var last = -1
return function(){
var _now = Date.now()
var current = Math.floor((_now - startTime) / duration)
if(current !== last){
count = 0
console.log(true)
last = current
}else if(count < times){
console.log(true)
}else{
console.log(false)
}
count++
}
}
var test = rateLimit(5000, 3);
setTimeout(function(){
test()
}, 800);
setTimeout(function(){
test()
}, 1800);
setTimeout(function(){
test()
}, 3000);
setTimeout(function(){
test()
}, 3600);
setTimeout(function(){
test()
}, 5001);
setTimeout(function(){
test()
}, 5003);
setTimeout(function(){
test()
}, 5004);
setTimeout(function(){
test()
}, 5005);
//output => true, true, true, false, true, true, true, false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment