How to detect when the user stops typing in JavaScript

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.