💻 Wait for User to Stop Typing, in JavaScript

• 4 min read • 1545 votes

Updated

Let’s say you have a search feature on your website that you want to live-update while the user types. The naive implementation would be to send a query to your server on every keystroke. This quickly falls apart, however, because users easily type faster than your server can respond. This makes for a poor user experience and created unnecessary load on your server.

A better solution is to execute the search only after the user stops typing. Implementing this is fairly simple once you understand how to debounce a function, which we’ll learn in this post.

Step 1. Listen For User Input

To start our demonstration, let’s implement that naive solution mentioned in the introduction. We’ll create an HTML <input/> and add an event listener that will be called whenever the input’s value is changed.

<!-- a simple input box -->
<input type="text" id="my-input" />
// Get the input box
let input = document.querySelector('#my-input');

// Add an event listener to monitor changes
input.addEventListener('keyup', function (e) {
    console.log('Value:', input.value);
});

Demo 1 – Output on Every Keystroke

Value: ""

There’s nothing wrong with performing a console.log on every keystroke, it works just fine and is very performant. However, if that log message was replaced by a slow network call, the server wouldn’t be able to respond quickly enough. On top of that, since the user is still typing, updating the interface to show the results wouldn’t be useful anyway. Let’s fix it.

Step 2. Debounce Event Handler Function

In order to execute an event listener (or any function for that matter) after the user stops typing, we need to know about the two built-in JavaScript methods setTimeout(callback, milliseconds) and clearTimeout(timeout):

setTimeout is a JavaScript method that executes a provided function after a specified amount of time (in milliseconds). clearTimeout is a related method that can be used to cancel a timeout that has been queued.

So how do we use these things to detect when a user stops typing? Here’s some well-documented code to demonstrate.

// Get the input box
let input = document.getElementById('my-input');

// Init a timeout variable to be used below
let timeout = null;

// Listen for keystroke events
input.addEventListener('keyup', function (e) {
    // Clear the timeout if it has already been set.
    // This will prevent the previous task from executing
    // if it has been less than <MILLISECONDS>
    clearTimeout(timeout);

    // Make a new timeout set to go off in 1000ms (1 second)
    timeout = setTimeout(function () {
        console.log('Input Value:', textInput.value);
    }, 1000);
});

Demo 2 – Output when Typing Stops

Value: ""

Typing in the input box above, you can see that nothing is outputted until no key is pressed for 1 second—exactly what we want. 😃

Now look what you've done 🌋
Stop clicking and run for your life! 😱
Uh oh, I don't think the system can't handle it! 🔥
Stop it, you're too kind 😄
Thanks for the love! ❤️
Thanks, glad you enjoyed it! Care to share?
HN Reddit

More Posts ✍🏻

See All »
• 6 min read • 80 votes
👆🏻 Creating a Pure CSS Dropdown Using the :hove...
Read Post »
• 4 min read • 3814 votes
😈 Productive Procrastination
Read Post »
• 3 min read • 246 votes
✨ HTML Share Buttons
Read Post »
• 8 min read • 339 votes
🚜 A Simple Web Scraper in Go
Read Post »
• 6 min read • 86 votes
👔 Quit With Positivity
Read Post »
• 5 min read • 404 votes
🚀 Getting Over the Fear of Launching
Read Post »
• 1 min read • 1 votes
🐄 Add Colorful Cows to Your Terminal
Read Post »

Be the first to hear about posts, right in your inbox 💌