JAVASCRIPT

Debounce API Calls for User Input to Prevent Over-fetching

Optimize API performance and prevent excessive requests by implementing a debounce function for user input fields, such as search bars and text inputs.

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

// Example API call function
async function searchAPI(query) {
  if (query.length < 3) {
    console.log('Query too short, not searching.');
    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);
  } catch (error) {
    console.error('Error during API search:', error);
  }
}

// Debounce the API search function
const debouncedSearch = debounce(searchAPI, 500); // Wait 500ms after last keystroke

// Attach to an input field
// const searchInput = document.getElementById('searchInput');
// searchInput.addEventListener('input', (event) => {
//   debouncedSearch(event.target.value);
// });

// Manual test example:
// debouncedSearch('apple'); // Called immediately, but timer starts
// debouncedSearch('app');   // Resets timer
// debouncedSearch('appl');  // Resets timer
// // ... 500ms pause ...
// // searchAPI('appl') is finally called once.
How it works: This JavaScript snippet implements a `debounce` utility function, essential for optimizing API calls triggered by frequent user input, like typing in a search box. Debouncing ensures that a function is only executed after a specified delay has passed since the *last* time it was invoked. This prevents making an API request on every keystroke, significantly reducing the load on your server and improving frontend performance by limiting unnecessary requests. The example applies this to an `searchAPI` function, ensuring it's only called when the user pauses typing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs