createSemaphore
Creates a semaphore limiting concurrent access to permits holders at a time, queueing
excess acquire() callers in FIFO order (first to call acquire is first granted a
permit when one frees up).
A factory function rather than a class, matching this package’s other stateful helpers
(debounce, throttle): the returned object closes over its internal queue/counter.
Use for concurrency limiting, e.g. rate-limiting calls to an external API. For mutual-exclusion (at most one holder), see createMutex, which is a semaphore with one permit.
Available since v3.0.4
Import
Section titled “Import”Signature
Section titled “Signature”Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
permits | number | Maximum number of concurrent holders. Must be `>= 1` (`Infinity` is accepted, for an effectively uncapped semaphore); a non-integer is floored (`2.9` behaves as `2`). |
Returns
Section titled “Returns”Semaphore — A Semaphore
Examples
Section titled “Examples”Limit concurrent calls to an external API
Section titled “Limit concurrent calls to an external API”At most permits calls run at once; the rest queue and wait their turn.
run() releases the permit even on error
Section titled “run() releases the permit even on error”Prefer run() over manual acquire()/release() — it cannot leak a permit.
Manual acquire() returns a one-shot release function
Section titled “Manual acquire() returns a one-shot release function”Calling the same release function twice throws — always caught, even under contention.
Related Types
Section titled “Related Types”Semaphore
Section titled “Semaphore”A semaphore created by createSemaphore.
