# How to detect when the user stops typing in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Mar 29, 2021. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-detect-user-stops-typing

> A quick hack to detect when the user stops typing text in an input field using JavaScript.

It is pretty common to [listen](https://attacomsian.com/blog/javascript-dom-add-an-event-handler) 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:

```html
<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:

```javascript
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:

```javascript
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);
});
```
