Lodash debounce not working when placed inside a method

I am trying to implement a debounce on an input field using the lodash debounce function.
It works fine if I addd the loadash debounce directly as the event handler but not if I place it inside another function.
The reason I need to do this is because I need to perform some action before debouncing the input field.
So I tried to place the debounce inside a vue method but then the debounce doesnt work.

Repro link:
https://jsfiddle.net/ab0fy342/4/

Input 1 debounces fine, but input 2 doesnt.

Hi

Your callback is a function and inside it is this not pointing to the component any more. Use an arrow function for your callback. It doesn’t change this

triggerUpdate2(event){
    // perform some action before debouncing
    	 _.debounce(() => {
			this.updateForm(event)
		}, 500)
    } ,

That still won’t work as this code will create a new, debounced copy of the updateForm method each time but never call it. and if you call it, you call a fresh copy each time so no debouncing will happen.

3 Likes

@johandalabacka have already tried the arrow function.
Doesn’t work.

@LinusBorg
Is there any other way to achieve what I want?

move the part that you need to debounce into its own method and debounce that (like you did in the codepen for he first method).

Then you can call the debounced method from the event handler method.

It’s also better to debounce each instance method dynamically during created, otherwise component instances that the same debounced function and that can lead to wonky debounce behaviour:

created() {
  this.updateForm = _.debounce(this.updateForm, 500)
},
methods: {
    triggerUpdate(event){
      // perform some action before debouncing
     this.updateForm(event)
    } ,
    updateForm: (event){
     console.log('in update')
    }
7 Likes