Debounce technique in LWC

Debouncing is a technique to make sure that the time consuming functions aren’t called too frequently.

Debouncing is a technique to make sure that the time consuming functions aren’t called too frequently.

The most common use case is when user is typing in search input and search method is being called. That call should be triggered only when user stops typing.

But it can be used in many cases - like preventing user from double-clicking buttons.

The usual timeout value is between 300 and 500 ms, anything around 1s might cause feeling of “delay”.

Here’s how to prevent calling the search function on every change event.

markup
<template>
    <lightning-input
        type="search"
        label="Search"
        onchange={handleChange}
    ></lightning-input>
</template>
javascript
import { LightningElement } from 'lwc';
const DEBOUNCE = 300;

export default class DebounceInput extends LightningElement {
    debounce;

    handleChange(event) {
        clearTimeout(this.debounce);
        // eslint-disable-next-line @lwc/lwc/no-async-operation
        this.debounce = setTimeout(() => {
            this.searchFunction(event.detail.value);
        }, DEBOUNCE);
    }

    searchFunction(search) {
        // call search function
        console.log(search);
    }
}

Text and code were extracted from the original slide. Plain-text version of the whole catalog