QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

Rate Limit Function

Limits how often a function can be executed within a given time window.

  • function
  • rate-limiting

Install

npx shadcn@latest add https://quicksnip.dev/r/rate-limit-function.json

This snippet is not verified yet. Review it before use, or help verify it.

Code

const rateLimit = (func, limit, timeWindow) => {
  let queue = [];
  setInterval(() => {
    if (queue.length) {
      const next = queue.shift();
      func(...next.args);
    }
  }, timeWindow);
  return (...args) => {
    if (queue.length < limit) {
      queue.push({ args });
    }
  };
};

Usage

const fetchData = () => console.log('Fetching data...');
const rateLimitedFetch = rateLimit(fetchData, 2, 1000);
setInterval(() => rateLimitedFetch(), 200); // Limits fetchData calls to twice a seconds