JAVASCRIPT

Implementing Client-Side API Rate Limiting with a Throttler

Prevent overwhelming external APIs by implementing a client-side throttling mechanism using JavaScript, ensuring calls adhere to rate limits and improve integration stability.

const throttle = (func, delay) => {
  let timeoutId;
  let lastArgs;
  let lastThis;

  return function(...args) {
    lastArgs = args;
    lastThis = this;

    if (!timeoutId) {
      timeoutId = setTimeout(() => {
        func.apply(lastThis, lastArgs);
        timeoutId = null;
        lastArgs = null;
        lastThis = null;
      }, delay);
    }
  };
};

// Example usage with an API call
const fetchData = async (query) => {
  console.log(`Fetching data for: ${query} at ${new Date().toLocaleTimeString()}`);
  try {
    const response = await fetch(`https://api.example.com/search?q=${query}`);
    const data = await response.json();
    console.log('API Response:', data);
  } catch (error) {
    console.error('API Error:', error);
  }
};

const throttledFetch = throttle(fetchData, 2000); // Allow calls every 2 seconds

// Simulate rapid calls
throttledFetch('item A');
throttledFetch('item B');
throttledFetch('item C');

setTimeout(() => throttledFetch('item D'), 1000); // This will be ignored due to throttling
setTimeout(() => throttledFetch('item E'), 2500); // This will execute after item C's execution + 2s delay
setTimeout(() => throttledFetch('item F'), 5000); // This will execute
How it works: This snippet demonstrates a client-side throttling utility in JavaScript to limit the frequency of API calls. The `throttle` function takes a function and a delay, returning a new function. When the throttled function is called repeatedly, it ensures that the original function executes at most once within the specified `delay` period. Subsequent calls within the delay period are ignored, but the arguments of the *last* call are preserved and used for the next allowed execution. This is crucial for integrating with APIs that have strict rate limits, preventing your application from overwhelming the API server or incurring penalties.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs