Make the function call-rate limiting a generic thing and use it in more places.
This commit is contained in:
parent
75ff4f0f95
commit
63776509a6
4 changed files with 49 additions and 34 deletions
39
src/ratelimitedfunc.js
Normal file
39
src/ratelimitedfunc.js
Normal file
|
@ -0,0 +1,39 @@
|
|||
/*
|
||||
Copyright 2016 OpenMarket Ltd
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
module.exports = function(f, min_interval_ms) {
|
||||
this.lastCall = 0;
|
||||
this.scheduledCall = undefined;
|
||||
|
||||
var self = this;
|
||||
return function() {
|
||||
var now = Date.now();
|
||||
|
||||
if (self.lastCall < now - min_interval_ms) {
|
||||
f.apply(this);
|
||||
self.lastCall = now;
|
||||
} else if (self.scheduledCall === undefined) {
|
||||
self.scheduledCall = setTimeout(() => {
|
||||
self.scheduledCall = undefined;
|
||||
f.apply(this);
|
||||
self.lastCall = now;
|
||||
},
|
||||
(self.lastCall + min_interval_ms) - now
|
||||
);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue