<div class="container">
    <h2>Debounce Example – Optimized API Search</h2>
    <input type="text" id="userSearch" placeholder="Search users by name..." />
    <div class="stats">
        <p><strong>Typing events:</strong> <span id="typingCount">0</span></p>
        <p><strong>API calls made:</strong> <span id="apiCallCount">0</span></p>
    </div>
    <ul id="userList"></ul>
</div>
body {
    font-family: Arial, sans-serif;
    padding: 20px;
}

.container {
    max-width: 400px;
    margin: 0 auto;
}

input {
    width: 100%;
    padding: 10px;
    font-size: 16px;
    margin-bottom: 20px;
}

.stats {
    margin-bottom: 20px;
}

ul {
    list-style-type: none;
    padding: 0;
}

li {
    background-color: #f9f9f9;
    margin: 5px 0;
    padding: 10px;
    border-radius: 4px;
}
const userSearch = document.getElementById('userSearch');
const userList = document.getElementById('userList');
const typingCountEl = document.getElementById('typingCount');
const apiCallCountEl = document.getElementById('apiCallCount');

let typingCount = 0;
let apiCallCount = 0;

// Debounce utility
function debounce(fn, delay = 500) {
    let timeoutId;
    return (...args) => {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
            fn.apply(this, args);
        }, delay);
    };
}

// Fetch users from JSONPlaceholder API
async function fetchUsers(query) {
    apiCallCount++;
    apiCallCountEl.textContent = apiCallCount;

    if (!query.trim()) {
        userList.innerHTML = '';
        return;
    }

    const response = await fetch(`https://jsonplaceholder.typicode.com/users`);
    const users = await response.json();
    const filtered = users.filter(user => user.name.toLowerCase().includes(query.toLowerCase()));
    userList.innerHTML = filtered.map(user => `<li>${user.name} (${user.email})</li>`).join('') || '<li>No users found</li>';
}

// Debounced version of fetchUsers
const debouncedFetch = debounce((e) => {
    fetchUsers(e.target.value);
}, 500);

// Event listener
userSearch.addEventListener('input', (e) => {
    typingCount++;
    typingCountEl.textContent = typingCount;
    debouncedFetch(e);
});
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.