Efficient User Input Delay in JavaScript & TypeScript

Observing keystroke activities (like keypress, keyup, and keydown) is a commonplace tactic in JavaScript to provide interactive user experiences. However, there may be scenarios where it is beneficial to identify when a user has finished typing in an input field.

Imagine, for instance, you have the following search form embedded in your webpage:

<form>
    <input type="search" id="input-text" placeholder="Start typing....">
</form>

Our objective is to incorporate a real-time search capability into this form, enabling the display of search results as the user types. A basic approach would involve attaching a keyup event to the input element, and then initiate an HTTP request for each character inputted by the user to retrieve search results:

const input = document.querySelector('#input-text');

// Attach a `keyup` event listener
input.addEventListener('keyup', (e) => {
    const text = e.currentTarget.value;
    // Do your work after
});

While this solution is functional, it is far from being efficient. It can result in numerous simultaneous requests to the server as the user continues to type, causing unnecessary load.

By tweaking this code slightly, we can enhance its effectiveness and performance considerably.

The proposed strategy involves monitoring the user’s input, and initiating the HTTP request only once the user has finished typing:

function observeInput(selector) {
    let timer;              // Timer identifier
    const waitTime = 500;   // Set wait time in milliseconds 

    // Define the search function
    const search = (text) => {
        // Do your work after
    };

    // Attach a `keyup` event listener
    const input = document.querySelector(selector);
    input.addEventListener('keyup', (e) => {
        const text = e.currentTarget.value;

        clearTimeout(timer);

        // Initiate the search request after a delay
        timer = setTimeout(() => {
            search(text);
        }, waitTime);
    });
}

observeInput('#input-text');

observeInput is a reusable function that can be attached to any input.

This optimized solution ensures a better balance between providing a dynamic search experience and efficient server request handling.

Typescript version

If you’re like me, someone who loves Typescript, then you’ll appreciate the next block of code:

function observeInput(selector: string): void {
    let timer: ReturnType<typeof setTimeout>;  // Timer identifier
    const waitTime: number = 500;              // Set wait time in milliseconds 

    // Define the search function
    const search = (text: string) => {
        // Do your work after
    };

    // Attach a `keyup` event listener
    const input = document.querySelector(selector);
    if (input) {
        input.addEventListener('keyup', (e: KeyboardEvent) => {
            const target = e.target as HTMLInputElement;
            const text = target.value;

            clearTimeout(timer);

            // Initiate the search request after a delay
            timer = setTimeout(() => {
                search(text);
            }, waitTime);
        });
    }
}

observeInput('#input-text');

That’s it for now! Have a fantastic time implementing these improvements and optimizing your application. As always, happy coding!

Member since January 2, 2019

As a seasoned WordPress developer with expertise in various tech stacks and languages, I bring years of experience to every project I handle. My passion for coding and dedication to delivering exceptional work ensures that each project I take on is of the highest quality. I specialize in creating custom themes, developing plugins, and building full-scale web systems. By staying up-to-date with the latest industry trends and best practices, I incorporate cutting-edge solutions into my work.

Comments

    Your email address will not be published. Required fields are marked *