It is pretty common to listen for keystroke events (keypress
, keyup
, and keydown
) to input elements to perform different tasks. But sometimes, you want to know when the user stops entering text in an input field.
Let us say that you have got the following HTML search form on your website:
<form>
<input type="search" id="input-text" placeholder="Start typing....">
</form>
We want to add a live search to this form and display search results while the user types. One possible way is to attach a keyup
event to the input
element and send an HTTP request for each character entered to the server to fetch search results:
const input = document.querySelector('#input-text');
// Listen for `keyup` event
input.addEventListener('keyup', (e) => {
const text = e.currentTarget.value;
// TODO: Make HTTP Request Here
});
The above solution should work fine, but it is not an optimal way of solving this problem. You'll end up sending dozens of concurrent requests to the server as the user keeps typing.
With a few modifications, we can easily make the above code more practical and more performant.
The idea is to keep track of the user's input and only make an HTTP request when the user has stopped typing:
let timer; // Timer identifier
const waitTime = 500; // Wait time in milliseconds
// Search function
const search = (text) => {
// TODO: Make HTTP Request HERE
};
// Listen for `keyup` event
const input = document.querySelector('#input-text');
input.addEventListener('keyup', (e) => {
const text = e.currentTarget.value;
// Clear timer
clearTimeout(timer);
// Wait for X ms and then process the request
timer = setTimeout(() => {
search(text);
}, waitTime);
});
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.