Source Code: (back to article)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Debounced Input Example</title>
<script>
// Debounce function to limit the rate at which a function is executed
function debounce(func, wait) {
let timeout;

return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};

clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}

// Function to be debounced
function fetchData(input) {
alert(`API call with input: ${input}`); // Placeholder for an API call
}

// Create a debounced version of fetchData
const debouncedFetchData = debounce(fetchData, 300);

// Add the debounced function to an event listener
function setup() {
document.getElementById('searchInput').addEventListener('input', (event) => {
debouncedFetchData(event.target.value);
});
}