May 21, 2018

Improve Your App Performance with Event Debouncing

If you have a text input that fires an AJAX request each time the user types something into it, it would be inefficient not to delay between each keystroke before firing the request. Adding this delay makes your UI more responsive.

Another example where we would need to add this delay is when the user resizes the window. In most cases it’s not necessary to listen to every single resize event to do the needed task. So instead of listening to 10 different resize events, it’s enough to listen to one or two.

Adding this delay between events is what we call debouncing.

Debouncing your events in Vue is very easy. You just need to wrap your event method with a debounce function. And in that function you need to specify the delay between events in milliseconds.

While it’s easy to implement your debounce function, it’s common to use the lodash’s debounce function.

Search input example

The most popular example on debouncing is debouncing a search input. So let’s say you have a search input that performs an AJAX request to display the results below it in a dropdown.

<template>
  <div>
    <input :value="keyword" @input="onInput($event.target.value)" />
  </div>
</template>

<script>
  import _ from 'lodash'

  export default {
    data() {
      return {
        keyword: ''
      }
    },

    watch: {
      keyword() {
        console.log('Send an AJAX Request')
      }
    },

    methods: {
      onInput: _.debounce(function (value) {
        this.keyword = value
      }, 500) // delay 500ms after each keystroke
    }
  }
</script>

Window resize example

Debouncing any event should be the same. Let’s, however, finish up this tutorial with this example on debouncing window resize:

<script>
  import _ from 'lodash'

  export default {
    mounted() {
      window.addEventListener('resize', this.onWindowResize)
    },

    destroyed() {
      window.removeEventListener('resize', this.onWindowResize)
    },

    methods: {
      onWindowResize: _.debounce(function () {
        console.log('window resized!')
      }, 100) // delay 100ms between resize events
    }
  }
</script>
Stay up-to-date on the latest projects and articles from me