Counted Semaphore for Resource Limits
Limit how many callers may hold a resource at once with a counted semaphore that queues waiters and releases permits fairly.
Code
export function createSemaphore(permits) {
let available = permits;
const waiters = [];
return {
async acquire() {
if (available > 0) {
available--;
return () => release();
}
await new Promise((resolve) => waiters.push(resolve));
return () => release();
},
};
function release() {
const next = waiters.shift();
if (next) next();
else available++;
}
}How the snippet works
The snippet is organized around the functions createSemaphore and release.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
The return value is newly constructed — inputs are never handed back.
Applying it
The primary signature is export function createSemaphore(permits)
createSemaphore is the public entry point; everything else in the file exists to support it.
Statements that matter
await new Promise((resolve) => waiters.push(resolve));
return () => release();
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.
FAQ
- Does `createSemaphore` modify its input?
- No. Nothing passed in is written to, which makes the call safe on shared data.
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `createSemaphore`, `release` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.