xavi- / node-simple-rate-limiter

A simple way to rate limit how often a function is executed.
76 stars 10 forks source link

Set context on for rate limited function #7

Closed jacksongross closed 1 year ago

jacksongross commented 8 years ago

Hi there, really liking the simplicity of this module. However, it would be nice if we could possibly pass a this argument to limit so that the function is called while preserving the context in which it would originally be called.

For example:

var SomeFn = function() {
  this.value = 'something';

  this.getSomething = function() {
    return this.value;
  }

  limit(this.getSomething, this).to(10).per(1000);
}

var obj = new SomeFn();
obj.getSomething(); // returns 'something'
greg5green commented 7 years ago

Another choice might be to store the this context that the method was invoked with in the queue array and use it when invoking the method later on. This would allow another level of abstraction and let you use the method exactly as you'd expect your non-limited method to behave.

Right now, it was simple enough to just use bind (limit(this.getSomething.bind(this)).to(10).per(1000), which looked a little goofy, but worked fine. Both this way and explicitly passing the this context to the module make things a little harder to use since you need to be aware of what value the method is bound to, whereas a more implicit way (like mentioned above) lets you forget that your method is even rate limited.

@xavi- If like either of these implementations and want to see them in your project, reply and I'll whip either one of them up into a PR for you.

xavi- commented 1 year ago

Excellent suggestion. Should be added in the next release