JAVASCRIPT

Debounce API Calls for Efficient Client-Side Integration

Optimize client-side API integrations by implementing a debouncing function in JavaScript, preventing excessive calls and reducing server load, especially for search inputs.

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

// Example API integration function
async function searchProducts(query) {
    if (!query) {
        console.log("Search query is empty.");
        return [];
    }
    console.log(`Fetching products for: "${query}"...`);
    try {
        const response = await fetch(`https://api.example.com/products?q=${encodeURIComponent(query)}`);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        console.log("Search results:", data);
        return data;
    } catch (error) {
        console.error("Error fetching products:", error);
        return [];
    }
}

// Debounced version of the search function, waits 500ms after last input
const debouncedSearchProducts = debounce(searchProducts, 500);

// --- Usage Example (e.g., in an input field's 'input' event listener) ---
document.addEventListener('DOMContentLoaded', () => {
    const searchInput = document.getElementById('search-input');
    if (searchInput) {
        searchInput.addEventListener('input', (event) => {
            const query = event.target.value;
            debouncedSearchProducts(query);
        });
    } else {
        console.warn("Element with ID 'search-input' not found.");
        // Manual test example if no input element:
        // debouncedSearchProducts("laptop");
        // setTimeout(() => debouncedSearchProducts("smartwatch"), 200); // This will be ignored
        // setTimeout(() => debouncedSearchProducts("smartphone"), 800); // This will trigger after 500ms
    }
});

// Assume an HTML structure like: <input type="text" id="search-input" placeholder="Search products...">
How it works: This snippet provides a client-side `debounce` utility function in JavaScript to optimize API calls. When integrated with user input (like a search bar), it ensures that the `searchProducts` function is only called after a specified `delay` has passed since the *last* input event. This prevents excessive and potentially rate-limited API requests from firing with every keystroke, significantly improving performance and reducing server load for interactive elements.

Need help integrating this into your project?

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

Hire DigitalCodeLabs