How to delay watcher method call on an input field

I have a situation like this:

I have a text field where the user writes in a barcode or the barcode gets written in by a Bluetooth HID. I want to delay the execution of the method associated with watch by 200-300ms (wait until the user writes in the complete code) and only then fire the associated method.

What you want is called to “debounce” your function.

https://www.npmjs.com/package/debounce

import debounce from 'debounce'


methods: {
  yourMethod() {
    // ...
  }
},
created(() {
  // when the component has been created, 
  // we replaced the original method with a debounced version 
  this.yourMethod = debounce(this.yourMethod, 300)
}

now execution of myMethod will be delayed until the user hasn’t typed anything for 300ms

3 Likes

Thanks LinusBorg, this is very helpful. I have a page requires to use multiple debounce function on multiple input components. If I use the debounce function directly there is only one component can work. Now, with this appoarch, the debounce function withs well on multiple components for me.