[SalesForce] How to add delay in onchange event in LWC

I have below input field in LWC

HTML:

<lightning-input variant="label-hidden" type="number"
    data-key={lineItem.lineItemId} label="percentageValue"
    onchange={percentageChange} style="width: 85px;"
    placeholder="Percente" step="0.01">

JS:

percentageChange(event) {
    console.log(event.target.value);
}

If I press 123 in the input text box, I get console log as:

1

12

123

… instead of just 123. Can anyone please suggest, how to add a little delay so that the onchange only picks up the value, when user has finished typing?!

Best Answer

You can't "delay" the event explicitly (though some browsers may choose to only fire them periodically), but you could build in a delay for potentially expensive processing:

onChangeHandler(event) {
    clearTimeout(this.timeoutId); // no-op if invalid id
    this.timeoutId = setTimeout(this.doExpensiveThing.bind(this), 500); // Adjust as necessary
}
doExpensiveThing() {
    // Do something here
}

This example code will wait until no new changes have occurred for at least half a second.

Edit: Playground, LWC Recipes Example

Related Topic