JAVASCRIPT
Implementing API Request Debouncing to Limit Excessive Calls
Optimize API performance by debouncing requests in JavaScript. This snippet shows how to prevent excessive API calls, improving responsiveness 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);
};
}
async function searchAPI(query) {
console.log('Calling API with query:', query);
// Simulate API call
return new Promise(resolve => {
setTimeout(() => {
resolve({ results: [`Result for ${query}`] });
}, 500);
});
}
const debouncedSearch = debounce(searchAPI, 500); // Wait 500ms after last call
// Example Usage:
// Imagine this is tied to an input field's 'keyup' event
// debouncedSearch('initial');
// debouncedSearch('ini');
// debouncedSearch('init'); // Only this one will likely trigger after 500ms pause
// setTimeout(() => debouncedSearch('javascript'), 100);
// setTimeout(() => debouncedSearch('java'), 200);
// setTimeout(() => debouncedSearch('javas'), 300); // This will trigger
How it works: This JavaScript snippet shows how to implement a debouncing function to limit the frequency of API calls. It's particularly useful for event handlers like search input changes, where you want to wait for a user to stop typing before making an API request. The `debounce` function ensures that the `searchAPI` function is only executed after a specified `delay` has passed since the last invocation, preventing excessive network requests.