A simple way to limit how often a function is executed.
Currently works with node.js v0.10.1+ (and probably lower).
If you want to limit all requests:
var limit = ;var request = ;userIds
Or if you'd like to be a bit more fine grain and/or explicit:
var limit = ;var callApi =;userIds
var limited = limit(fn);
limited(args...): Enqueues a set of arguments that
fnwill be executed with. Returns an EventEmitter that will emit a
fnis executed with
args. Also, in the case that
fnreturns an EventEmitter, the events emmitted by the returned EventEmitter will be relayed to the EventEmitter returned by
limited. In other words, stuff like this works:var limit = ;var request = ;"";
limited.to(count=1): The number of times
fnwill be execute within the time specified by
limited.per(time=Infinity): The period of time in which
fnwill be executed
.to(count)number of times.
limited.evenly([toggle=true]): Off by default. When true,
fnwill be executed evenly through the time period specified by
.per(time). For example, if set to true and
fnwill be executed every 100ms.
limited.withFuzz([percent=0.1]): Set to 0 by default. Adds a random factor to the delay time. For example if set to 0.1 and
fnwill be executed between every 100ms to 110ms.
All methods attached to
limited and can be chained.
to method or
per can be called any number of times including zero. The effective default count for
to is 1 and the effective default interval for
per is Infinity. Which means if neither the
to method or
per method are called, then
limit will only execute
fn once ever:
var init = ;forvar i = 0; i < 3; i++ ;/*** Console output: ***/// $ Runs only once// ... Nothing else is ever printed ...
per is never called,
fn is executed at most
count number of times:
var dos = ;forvar i = 0; i < 3; i++ ;/*** Console output: ***/// $ twice only// $ twice only// ... Nothing else is ever printed ...
On the other hand, if
to is never called,
fn is only executed every
var tick = ;forvar i = 0; i < 3; i++ ;/*** Console output: ***/// $ Once a second// ... pause for 1 second ...// $ Once a second// ... pause for 1 second ...// $ Once a second
Finally, as mentioned earlier,
per can be called any number of times. Each time either
per is called, the previous
interval value is overriden:
var strange =;forvar i = 0; i < 3; i++ ;/*** Console output: ***/// $ Every once in a while// $ Every once in a while// ... pause for 2 second ...// $ Every once in a while
The easiest way to get simple-rate-limiter is with npm:
npm install simple-rate-limiter
Alternatively you can clone this git repository:
git clone git://github.com/xavi-/node-simple-rate-limiter.git
- Xavi Ramirez
This project is released under The MIT License.