How to detect when the user stops typing

eddieaich profile image Eddie Aich ・2 min read


It is common to add keystroke events to input elements to detect when a user is typing such as keypress, keydown, and keyup. But sometimes, these alone are too granular for your needs. Imagine sending a Fetch request to your server to update a DB record after every keystroke!

With just a little bit of code, we can make handling user keystrokes more practical and more performant.

Practical applications

  1. Implement an auto-save feature
  2. Keep your local data store up-to-date
  3. Synchronize the view with real-time collaborators

Here's what you're going to build

Let's define some basic variables

let timer,
    timeoutVal = 1000; // time it takes to wait for user to stop typing in ms

// pointers to our simple DOM elements
const status = document.getElementById('status');
const typer = document.getElementById('typer');

Add two separate event listeners on keypress and keyup

// detects when the user is actively typing
typer.addEventListener('keypress', handleKeyPress);
// triggers a check to see if the user is actually done typing
typer.addEventListener('keyup', handleKeyUp);

Create a timeout on keyup event

// when the user has stopped pressing on keys, set the timeout
// if the user presses on keys before the timeout is reached, then this timeout should be canceled via the keypress event
function handleKeyUp(e) {
  window.clearTimeout(timer); // prevent errant multiple timeouts from being generated
  timer = window.setTimeout(() => {
  status.innerHTML = 'All done typing! Do stuff like save content to DB, send WebSocket message to server, etc.';
  }, timeoutVal);

Clear the timeout object on keypress

// when user is pressing down on keys, clear the timeout
// a keyup event always follows a keypress event so the timeout will be re-initiated there
function handleKeyPress(e) {
  status.innerHTML = 'Typing...';

That's it!

See how simple that was? Now you can make a more accurate determination on when the user has stopped typing and process data more intelligently.

Make it better - other things to think about!

  1. How would you handle Backspace events?
  2. How would you handle version control?

Follow me on Twitter https://twitter.com/eddieaich


Editor guide