Debounced Search Input with Watchers
Implement a debounced search input that updates result reactively after a specific delay, highlighting the use of watchers to reduce unnecessary operations.
<!-- HTML structure for the search input field -->
<div id="search-wrapper">
<input type="text" id="search-input" placeholder="Search..."/>
<div id="search-results"></div>
</div>
This HTML snippet creates a search input and a container where search results will be displayed.
/* CSS styles for the search input and results container */
#search-wrapper {
position: relative;
}
#search-input {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
margin-bottom: 10px;
}
#search-results {
position: absolute;
width: calc(100% - 20px);
border: 1px solid #ccc;
background: #fff;
max-height: 200px;
overflow-y: auto;
}
CSS styles for the search interface, ensuring a neat and readable layout for the input and results elements.
// JavaScript to handle debounced search input
const searchInput = document.getElementById('search-input');
const searchResults = document.getElementById('search-results');
let debounceTimeout = null;
function search(query) {
// Simulated search operation (e.g., fetching from an API)
console.log(`Searching for: ${query}`);
// Update the search-results div with search output
searchResults.textContent = 'Results for: ' + query;
}
searchInput.addEventListener('input', (event) => {
const query = event.target.value.trim();
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(() => {
if (query.length > 2) { // Assuming we only search for a query of min 3 characters
search(query);
} else {
searchResults.textContent = '';
}
}, 300); // Debounce delay of 300ms
});
JavaScript code sets up a debounce mechanism that listens to input changes from the search field. It delays the search operation (in this example a console log and text update) until 300 milliseconds after the last user input in an attempt to minimize unnecessary operations, assuming a minimum search query length of 3 characters.