Debug School

rakesh kumar
rakesh kumar

Posted on

How to Adding Debounce for Events in Vue.js

Debounce for Events
how-to-implement-debounce
How-to-implement-debounce
using-debounce-in-vue-js-templates

Adding Debounce for Events
We can delay the execution of event handlers by using the debounce NPM package by writing:

<input @input="debounceInput">
methods: {
  debounceInput: debounce(function (e) {
    this.$store.dispatch('updateValue', e.target.value)
  }, 200)
}
Enter fullscreen mode Exit fullscreen mode

We can use debounce by using the debounce function from the package.

The function that we pass inside will run after a given amount of time.

We passed in 200 in the second argument, so the function is delay 200 milliseconds.

We can also use the debounce Lodash method, we can write:

<input @input="debounceInput">
methods: {
  debounceInput: _.debounce(function (e) {
    this.$store.dispatch('updateValue', e.target.value)
  }, 200)
}
Enter fullscreen mode Exit fullscreen mode

Then we get the same result.

How to implement debounce in vue3

I have a filter input field and want to filter a list of items. The list is large so I want to use debounce to delay the filter being applied until the user has stopped typing for improved user experience. This is my input field and it's bound to filterText that is used to filter the list.

<input type="text" v-model="state.filterText" />

Hi first time answering something here, so correct my answer as much as you want, I'd appreciate it. I think that the prettiest and lightest solution is to create a directive globally that you can use as much as you want in all of your forms.

you first create the file with your directive, eg. debouncer.js

and you create the function for the debouncing

//debouncer.js
/*
  This is the typical debouncer function that receives
  the "callback" and the time it will wait to emit the event
*/
Enter fullscreen mode Exit fullscreen mode
    function debouncer (fn, delay) {
        var timeoutID = null
        return function () {
          clearTimeout(timeoutID)
          var args = arguments
          var that = this
          timeoutID = setTimeout(function () {
            fn.apply(that, args)
          }, delay)
        }
      }
Enter fullscreen mode Exit fullscreen mode
/*
  this function receives the element where the directive
  will be set in and also the value set in it
  if the value has changed then it will rebind the event
  it has a default timeout of 500 milliseconds
*/
Enter fullscreen mode Exit fullscreen mode
    module.exports = function debounce(el, binding) {
      if(binding.value !== binding.oldValue) {
        el.oninput = debouncer(function(){
          el.dispatchEvent(new Event('change'))
        }, parseInt(binding.value) || 500)
      }
    }
Enter fullscreen mode Exit fullscreen mode

After you define this file you can go to your main.js import it and use the exported function.

//main.js
import { createApp } from 'vue'
import debounce from './directives/debounce' // file being imported
Enter fullscreen mode Exit fullscreen mode
    const app = createApp(App)

    //defining the directive
    app.directive('debounce', (el,binding) => debounce(el,binding))

    app.mount('#app')
Enter fullscreen mode Exit fullscreen mode

And its done, when you want to use the directive on an input you simply do it like this, no imports or anything.

 //Component.vue
    <input
       :placeholder="filter by name"
       v-model.lazy="filter.value" v-debounce="400"
    />
Enter fullscreen mode Exit fullscreen mode

The v-model.lazy directive is important if you choose to do it this way, because by default it will update your binded property on the input event, but setting this will make it wait for a change event instead, which is the event we are emitting in our debounce function. Doing this will stop the v-model updating itself until you stop writing or the timeout runs out (which you can set in the value of the directive). I hope this was understandable.

Using it in Vue Templates

Using debounce in vue templates is just as easy. In your methods, include debounce before the main function.

import debounce from 'lodash'
methods: {
  onChange: debounce(function (e) {
    // change stuff here
  }, 450)
}
Enter fullscreen mode Exit fullscreen mode

That’s pretty much it! Whether the **onChange event **is called from another function or an event listener, the function should only be called at least 450 milliseconds apart. Handy function!

Top comments (0)