Rate Limiter (Sliding Window)
Rate Limiter (Sliding Window) is a reusable JavaScript snippet. Limits the rate of function calls using a sliding window algorithm. Ensures no more than `limit` calls within `windowMs` milliseconds. The full implementation: function rateLimiter(limit, windowMs) { const calls = [] return function(fn, ...args) { const now = Date.now() // Remove expired calls while (calls.length && calls[0] = limit) { const waitMs = calls[0] + windowMs - now throw new Error(`Rate limit exceeded. Try again in ${Math.ceil(waitMs / 1000)}s`) } calls.push(now) return fn(...args) } } // Per-key rate limiter (e.g., per user) function rateLimiterByKey(limit, windowMs) { const queues = new Map() return (key, fn, ...args) => { if (!queues.has(key)) queues.set(key, []) const calls… This snippet uses only standard JavaScript with no dependencies, so it runs in modern browsers and Node.js alike. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.