JAVASCRIPT

Debouncing API Calls for Search Inputs

Optimize user experience and reduce server load by implementing debouncing for API calls triggered by search inputs, preventing excessive requests.

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

async function searchAPI(query) {
  if (query.length < 3) { // Only search if query is at least 3 characters
    console.log('Query too short:', query);
    return [];
  }
  console.log('Searching for:', query);
  try {
    const response = await fetch(`https://api.example.com/search?q=${encodeURIComponent(query)}`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log('Search results:', data);
    return data.results; // Assuming API returns results in a 'results' field
  } catch (error) {
    console.error('Error during API search:', error);
    return [];
  }
}

// Example usage with an input field:
// const searchInput = document.getElementById('searchInput');
// const debouncedSearch = debounce(searchAPI, 500); // Wait 500ms after last keystroke

// searchInput.addEventListener('input', (event) => {
//   debouncedSearch(event.target.value);
// });
How it works: This snippet shows how to implement debouncing for API calls, particularly useful for search input fields. The `debounce` function wraps any function (like `searchAPI`), ensuring it's only called after a specified `delay` has passed without further invocations. This prevents the `searchAPI` from firing on every keystroke, significantly reducing the number of API requests and improving performance and 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