我们的web应用程序中有许多功能被调用得太频繁了。我们希望您创建一个函数,给定一个函数和一个时间间隔,返回一个新函数,我们可以随时调用它,但确保每个间隔调用原始函数的次数不超过一次。示例用法: limitedDoSomething = rateLimit(doSomething,500);现在,对
limitedDoSomething的调用只会调用doSomething,但不会超过每500毫秒调用一次。
function logHello(){ // just a sample function
console.log('Hello!');
}
limitedDoSomething = rateLimit(logHello, 500);
limitedDoSomething(); // should log “Hello!”
window.setTimeout(function(){
limitedDoSomething(); // should not log “Hello!"
}, 400);
window.setTimeout(function(){
limitedDoSomething(); // should log “Hello!"
}, 500);function rateLimit(func, limit){
var lastInvokedTimestamp;
return function(){
if(typeof lastInvokedTimestamp === 'undefined' || Date.now() - lastInvokedTimestamp >= limit){
lastInvokedTimestamp = Date.now();
console.log('go ahead!');
return func();
} else {
console.log('too early!');
return;
}
};
}
// run test cases
function logHello(){ // just a sample function
console.log('Hello!');
}
limitedDoSomething = rateLimit(logHello, 500);
limitedDoSomething(); // should log “Hello!”
window.setTimeout(function(){
limitedDoSomething(); // should not log “Hello!"
}, 400);
window.setTimeout(function(){
limitedDoSomething(); // should log “Hello!"
}, 500);我很想知道是否有办法改进我的解决方案。
发布于 2016-04-22 07:02:34
以下是我能想到的一些小改进。没什么大不了的:
lastInvokedTimestamp,这样就不会是undefined了。setTimeout。function rateLimit ( func, interval ) {
var nextInvokeTimestamp = 0;
return function(){
var now = Date.now();
if ( now < nextInvokeTimestamp ) {
return console.log('too early!');
}
nextInvokeTimestamp = now + interval;
console.log('go ahead!');
return func.apply( this, arguments );
};
}
// run test cases
function logHello( message ){
console.log( message || 'Hello!' );
}
limitedDoSomething = rateLimit( logHello, 500 );
limitedDoSomething( "Welcome!" ); // should log “Welcome!”
setTimeout( limitedDoSomething, 400 ); // should not log “Hello!"
setTimeout( limitedDoSomething, 500 ); // should log “Hello!"您可能会注意到,David是完全不同的做这事。
setTimeout将实际调用延迟到稍后的事件循环,而不是当前事件,以使事情稳定下来一些。这并不是好或坏,只是不同的需要不同的减速带而已。如果您的要求只是“将多个调用简化为一个”,那么您做得很好。
https://codereview.stackexchange.com/questions/126390
复制相似问题