JAVASCRIPT

Debouncing API Calls to Prevent Over-fetching

Optimize your web application by debouncing API requests, preventing excessive calls during rapid user interactions like typing in a search bar or scrolling.

function debounce(func, delay) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

// Example API call function
async function searchProducts(query) {
  console.log(`Searching for: ${query}...`);
  try {
    const response = await fetch(`https://api.example.com/products?q=${query}`);
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    const data = await response.json();
    console.log(`Search results for '${query}':`, data);
    return data;
  } catch (error) {
    console.error('Error during product search:', error);
  }
}

// Create a debounced version of the search function
const debouncedSearch = debounce(searchProducts, 500);

// Simulate rapid user input (e.g., typing into a search field)
// The API call will only be made once, 500ms after the last call to debouncedSearch
// debouncedSearch('laptop');
// debouncedSearch('laptops');
// debouncedSearch('gaming laptops'); // This will be the only one that triggers the actual API call

// Example using an actual input element (uncomment to test in browser):
// const inputElement = document.createElement('input');
// inputElement.type = 'text';
// inputElement.placeholder = 'Search products...';
// document.body.appendChild(inputElement);
// inputElement.addEventListener('input', (event) => {
//   debouncedSearch(event.target.value);
// });
How it works: This snippet provides a generic `debounce` function that can be used to limit the frequency of API calls. When a debounced function is called repeatedly, it will only execute the underlying function (in this case, `searchProducts`) after a specified `delay` has passed without any further calls. This is extremely useful for scenarios like search bars, where you want to fetch results only after the user has stopped typing for a short period, preventing excessive and unnecessary API requests.

Need help integrating this into your project?

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

Hire DigitalCodeLabs