For more tips like this, sign up to the weekly newsletter!

Debounce user inputs

If you have an input controller on a page which the user can interact with, you usually add some kind of event listener. For a simple text input, that would be the input event.

For example, it calls the handleInput for every key pressed:

input.addEventListener("input", handleInput);

But what if the handleInput is an expensive function? For example, it triggers a server request, and that could easily result in rate limiting. In that case, waiting for the user to stop typing and sending the request only after that makes sense.

This is where debounce comes into play.

This is a function that makes a debounced version of another function. When it is repeatedly called, it only calls the original one after some time is passed without invocations. It is perfect for handling user inputs that are coming in bursts.

Many libraries provide debounce functionality, and one such implementation is Lodash's.

To only call the handleInput after 1 second in inactivity, use:

input.addEventListener("input", _.debounce(handleInput, 1000));
Try it
Learn more: