JAVASCRIPT
Debouncing User Input for API Search Requests (Vanilla JS)
Implement a vanilla JavaScript debounce function to limit API calls during rapid user input, optimizing search functionality and reducing server load.
/**
* Debounce function to limit how often a function can be called.
* Useful for performance-sensitive tasks like API calls on user input.
*
* @param {function} func The function to debounce.
* @param {number} delay The delay in milliseconds after which the function will be executed.
* @returns {function} The debounced function.
*/
function debounce(func, delay) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), delay);
};
}
// Example API call function
async function searchAPI(query) {
if (!query.trim()) {
console.log('Search query is empty, not calling API.');
return;
}
console.log(`Searching for: "${query}"...`);
// Simulate API call
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('API search results:', data);
// Display results to the user
} catch (error) {
console.error('Search API error:', error);
}
}
// Create a debounced version of the searchAPI function
const debouncedSearch = debounce(searchAPI, 500); // Wait 500ms after user stops typing
// Example Usage:
// Assuming an HTML input: <input type="text" id="searchInput" placeholder="Search...">
// document.getElementById('searchInput')?.addEventListener('input', (event) => {
// const query = event.target.value;
// debouncedSearch(query);
// });
// Simulate rapid typing:
// debouncedSearch('a');
// debouncedSearch('ap');
// debouncedSearch('api'); // This one will likely trigger after 500ms
// setTimeout(() => debouncedSearch('api in'), 300);
// setTimeout(() => debouncedSearch('api integr'), 700); // This one will trigger
How it works: This snippet provides a vanilla JavaScript `debounce` utility function specifically tailored to optimize API search requests. When integrated with an input field, it ensures that the `searchAPI` function is only called after a specified delay (e.g., 500ms) has passed since the user last typed. This prevents excessive, redundant API calls during rapid typing, significantly reducing server load, improving performance, and enhancing the responsiveness of the application by minimizing unnecessary network traffic.