Blog>
Snippets

Using Debouncing for API Call Optimization

Provide an example of using debouncing to optimize API call frequency, particularly for features like search autocompletion or live content filtering.
let debounceTimer;
function debounceFunction(apiCall, delay) {
  // Clear the previous timer to reset the delay
  clearTimeout(debounceTimer);
  // Set a new timer
  debounceTimer = setTimeout(() => {
    apiCall();
  }, delay);
}
This code snippet defines a generic debounce function. It uses a timer to delay the execution of an API call. Each time the function is invoked, any existing timer is cleared and a new one is set. This ensures that the API call is only made after the user stops typing for a specified delay period, optimizing the frequency of API calls.
function searchAPI(query) {
  console.log(`Searching for: ${query}`);
  // Placeholder for actual API call
  // e.g., fetch(`/api/search?q=${query}`).then(...)
}
This function simulates an API call, logging the query to the console. In a real application, this would perform the actual API request to search based on the `query` parameter.
document.getElementById('searchInput').addEventListener('input', function(e) {
  debounceFunction(() => searchAPI(e.target.value), 500);
});
This code adds an input event listener to an HTML element with the id 'searchInput'. It uses the previously defined `debounceFunction` to delay the search API call until 500ms after the user stops typing, helping to reduce the overall number of API requests during search autocompletion or live filtering.