JAVASCRIPT

Debouncing API Calls for Real-time Search and Input

Implement a debounce function to limit the frequency of API calls triggered by user input, such as search fields, improving performance and reducing server load.

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

// --- Example API Integration ---
async function searchAPI(query) {
  if (!query.trim()) {
    console.log('Query is empty, not searching.');
    // Optionally clear results or show a message
    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);
    // Display results in UI
    return data;
  } catch (error) {
    console.error('Search API error:', error);
  }
}

// Debounced version of the search function
const debouncedSearch = debounce(searchAPI, 500); // Wait 500ms after last input

// Example Usage (attach to an input field):
// const searchInput = document.getElementById('searchInput');
// if (searchInput) {
//   searchInput.addEventListener('input', (event) => {
//     debouncedSearch(event.target.value);
//   });
// }
//
// // Simulate typing
// setTimeout(() => { if(searchInput) searchInput.value = 'hello'; searchInput.dispatchEvent(new Event('input')); }, 100);
// setTimeout(() => { if(searchInput) searchInput.value = 'hello w'; searchInput.dispatchEvent(new Event('input')); }, 200);
// setTimeout(() => { if(searchInput) searchInput.value = 'hello world'; searchInput.dispatchEvent(new Event('input')); }, 300); // Only this one will trigger after 500ms
How it works: This snippet provides a generic `debounce` function that wraps another function, delaying its execution until a certain amount of time has passed without further calls. It's particularly useful for API integrations where user input, such as typing into a search bar, would otherwise trigger excessive and unnecessary API requests. By debouncing `searchAPI` calls, the actual request is only made after the user pauses typing for a specified delay (e.g., 500ms), significantly reducing server load and improving client-side performance.

Need help integrating this into your project?

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

Hire DigitalCodeLabs