A large part of the web's interactivity relies on inputs, forms and textareas.

If you're building a simple website you can probably get away with anything, but if you are working on a web application that you're planning to scale, you should plan the requests you're sending a bit more carefully.

Hooking up Event Listeners to Inputs

The most common mistake I see beginners make is carelessly hook up event listeners to input type elements.

Weather an input should update some data on the server in real-time, or it should perform a search, the action should not be triggered by a key press on the keyboard.

Does the code below seem like a valid approach to fetch data from the server?

input.addEventListener('keyup', () => {
  // ✉️ Fetch or send data to the server
});

The Problem

The problem with sending a request on every keypress is that we are putting an unnecessary load on the server. This is an almost invisible problem during development or on a small scale; however, if you are in production with a few thousand users it makes a MASSIVE difference.

The Solution

A simple solution is to delay the request with a reasonable about of time, then cancel in on each subsequent keypress.

So, how we go about doing this?

We'll simply use Javascript's built in setTimeout and clearTimeout functions - something like this:

const delay = 300; // ⏱️ The delay time, in milliseconds
let timeout; // ⏲️ We'll store the timeout in here


input.addEventListener( "keyup", () => {
    if ( timeout ) clearTimeout( timeout ); // ❌ Clear the timeout
    
    timeout = setTimeout( () => {
      // ✉️ Fetch or send data to the server
    }, delay );
});

That's it. Your server will love you for it ❤️