JAVASCRIPT

Throttling & Debouncing API Requests for Performance

Optimize web application performance by implementing client-side throttling and debouncing techniques to control the frequency of API calls, preventing overload and improving user experience.

function createApiDebouncer(apiCallFunction, delay = 300) {
  let timeoutId;
  let lastArgs = null;
  let lastThis = null;
  let resolvePromise = null;
  let rejectPromise = null;

  const debounced = function(...args) {
    lastArgs = args;
    lastThis = this;
    
    // Return a new promise for each debounced call
    return new Promise((resolve, reject) => {
      resolvePromise = resolve;
      rejectPromise = reject;

      clearTimeout(timeoutId);
      timeoutId = setTimeout(async () => {
        try {
          const result = await apiCallFunction.apply(lastThis, lastArgs);
          if (resolvePromise) resolvePromise(result);
        } catch (error) {
          if (rejectPromise) rejectPromise(error);
        } finally {
          // Clear references after execution
          resolvePromise = null;
          rejectPromise = null;
          lastArgs = null;
          lastThis = null;
        }
      }, delay);
    });
  };

  // Optional: Add a throttle-like behavior if needed, or keep it pure debounce.
  // For this example, it focuses purely on debouncing the API call.

  return debounced;
}

// Example Usage:
// This example uses a mock API call for demonstration.
// async function searchApi(query) {
//   console.log(`Calling API for: "${query}"`);
//   return new Promise(resolve => setTimeout(() => resolve(`Results for "${query}"`), 500));
// }

// const debouncedSearchApi = createApiDebouncer(searchApi, 500);

// // Simulate fast typing
// // debouncedSearchApi('a').then(console.log);
// // debouncedSearchApi('ap').then(console.log);
// // debouncedSearchApi('app').then(console.log);
// // setTimeout(() => debouncedSearchApi('appl').then(console.log), 300); // 'app' will be ignored
// // setTimeout(() => debouncedSearchApi('apple').then(console.log), 600); // Only 'apple' will trigger API after 500ms delay.
// // The console will show:
// // Calling API for: "apple"
// // Results for "apple"
How it works: This snippet provides a higher-order function to debounce API calls. When a debounced function is called multiple times rapidly, it will only execute the underlying `apiCallFunction` once after a specified `delay` has passed since the last invocation. This is incredibly useful for optimizing performance by preventing excessive API requests, such as during "search-as-you-type" functionality, thereby reducing server load and improving the user experience.

Need help integrating this into your project?

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

Hire DigitalCodeLabs