Skip to content

Instantly share code, notes, and snippets.

@shesek
Created November 14, 2012 19:58
Show Gist options
  • Save shesek/4074385 to your computer and use it in GitHub Desktop.
Save shesek/4074385 to your computer and use it in GitHub Desktop.
Limit concurrency of async functions
# Returns a function that invokes `fn`, with maximum concurrency of `max`
# Generalized version of https://gist.github.com/4071443
concurrent = (free, fn) ->
queue = []
r = (a..., cb) ->
# Queue the call if we have too many running
return queue.push [a..., cb] unless free
--free
fn a..., (resp...) ->
++free
# Run the next queued request, if we have one
r queue.shift()... if queue.length
cb resp...
# Usage:
# To modify an existing function
limitedFoo = concurrent 15, foo
# And just use `limitedFoo()` like you would normally use `foo()`
# Or simply as a decorator
foo = concurrent 15, (cb) -> setTimeout cb, 1000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment