JAVASCRIPT
Debounce API Search Input to Prevent Excessive Requests
Learn to debounce user input for API search fields, effectively reducing the number of network requests made to your backend and optimizing server load and client performance.
function debounce(func, delay) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), delay);
};
}
// Function that simulates an API call
async function searchAPI(query) {
if (!query.trim()) {
console.log('Search query is empty, not calling API.');
return [];
}
console.log(`Calling API with query: "${query}"`);
// Simulate API call delay
return new Promise(resolve => {
setTimeout(() => {
resolve(`Results for "${query}"`);
}, 500);
});
}
// Debounced version of the searchAPI function
const debouncedSearch = debounce(searchAPI, 500); // Wait 500ms after user stops typing
// Example Usage with an input field:
// const searchInput = document.getElementById('searchInput');
// const resultsDiv = document.getElementById('results');
// searchInput.addEventListener('keyup', async (event) => {
// const query = event.target.value;
// const result = await debouncedSearch(query);
// if (result) {
// resultsDiv.textContent = result;
// } else {
// resultsDiv.textContent = 'Type to search...';
// }
// });
// HTML for example:
// <input type="text" id="searchInput" placeholder="Search...">
// <div id="results">Type to search...</div>
How it works: This snippet provides a `debounce` utility function that delays the execution of a function until after a certain amount of time has passed without it being called again. It's particularly useful for API integrations involving user input, like search fields. Instead of sending an API request with every keystroke, the `debouncedSearch` function ensures the `searchAPI` is only called after the user has paused typing for a specified `delay` (e.g., 500ms). This significantly reduces the number of unnecessary API calls, thereby saving server resources and improving frontend performance.