1

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 snuggest how to add little delay so that onchange only picks the value when use finished typing

6

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

  • thank you so much for responding, could you please confirm if this will increase the performance of the page, or it will add an extra load on the page, is it a best practice to use delay or is t fine if onchange is working on every single character I type. – gs650x Dec 2 '19 at 16:50
  • @gs650x If you're doing something expensive (hitting the server, rendering thousands of items, etc), the delay will make the page much more responsive, otherwise it doesn't matter. – sfdcfox Dec 2 '19 at 16:52
  • 2
    A working example you can find in this lwc reciepes – sanket kumar Dec 2 '19 at 16:53
  • @sanketkumar Thanks for that, I edited it in as well as a very short playground example I just wrote for this answer. – sfdcfox Dec 2 '19 at 16:54
  • Thank you so much sfdcfox and @sanketkumar – gs650x Dec 2 '19 at 17:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.