I'm writing something like a token bucket in CoffeeScript.
class TokenBucket
constructor: (@speed, @threshold) ->
@currentVolume = 0
@interval = setInterval =>
@currentVolume += 1
if @threshold < @currentVolume
@currentVolume = @threshold
, @speed * 1000
stop: ->
clearInterval @interval
return
get: ->
if @currentVolume == 0
false
else
@currentVolume -= 1
true
For people not comfortable with CoffeeScript, let me simply explain this. After constructing a TokenBucket
, it calls setInterval
with a callback that increments the "bucket" every few seconds.
The problem is, if the user forgets to call stop
before existing, the setInterval
is going to keep the Node.js process running, because the event loop will never be empty. What I want to do is to tell Node.js that this setInterval
in not important, you can terminate it if everything else is done. How can I achieve that?
stop
call?clearInterval
yourself when "everything else is done"?setInterval()
and exit