Source Code:
(back to article)
Submit
Result:
Report an issue
<!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); }); } // Ensure setup is called once the document is fully loaded document.addEventListener('DOMContentLoaded', setup); </script> </head> <body> <h3>Type in the input field:</h3> <input type="text" id="searchInput" placeholder="Start typing..."> </body> </html>