Skip to content

Instantly share code, notes, and snippets.

@mnutt
Created July 15, 2013 23:35
Show Gist options
  • Save mnutt/6004468 to your computer and use it in GitHub Desktop.
Save mnutt/6004468 to your computer and use it in GitHub Desktop.
Simple node.js concurrency limiter
# Limits concurrency to @limit requests at any given time.
#
# Every time limiter.run() is called, concurrent load is incremented by one and
# the function you pass into it is called with a single argument of the 'done'
# function. When your work is complete, call the 'done' function and the
# concurrent load will be decremented by one.
#
# Usage:
#
# ConcurrencyLimiter = require('limiter')
# limiter = new ConcurrencyLimiter(10)
#
# limiter.run (done) ->
# fnThatTakesALongTime (result) ->
# console.log result
# done()
#
# Only 10 fnThatTakesALongTime functions will be running at any given time. The
# rest will be queued and run asynchronously.
class ConcurrencyLimiter
constructor: (@limit) ->
@count = 0
@queue = []
run: (cb) ->
if @count <= @limit
@count += 1
console.log {count: @count, queue: @queue.length}
cb @done
else
@queue.push cb
done: =>
@count -= 1
@run(@queue.shift()) if @queue.length
module.exports = ConcurrencyLimiter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment