Throttling and Debouncing Events with Vue.js and lodash

Joshua Bemenderfer

Event throttling and debouncing are great ways to improve performance or lower network overhead. While Vue.js 1 used to have native support for throttling and debouncing events, it was removed in Vue 2 in the interest of keeping the core slim. As a result, the standard way of throttling and debouncing events in Vue 2 is now through lodash.

If you're a bit confused as to the difference between throttling and debouncing, css-tricks has a great article on the subject.

Installation

lodash can be installed through yarn or npm.

# Yarn
$ yarn add lodash
# NPM
$ npm install lodash --save

Note: If you don't want to import all of lodash, just the parts you need, a little webpack build customization should do the trick. You can also install and import parts of lodash separately, in packages like lodash.throttle and lodash.debounce.

Throttling Methods

Throttling your event handling methods is pretty easy. Just wrap the function you want to call in lodash’s _.throttle function. Throttling can be used to ensure your events are preserved, but separated over time.

MyComponent.vue

<template>
  <button @click="throttledMethod()">Click me as fast as you can!</button>
</template>

<script>
import _ from 'lodash'

export default {
  methods: {
    throttledMethod: _.throttle(() => {
      console.log('I get fired every two seconds!')
    }, 2000)
  }
}
</script>

Debouncing Methods

While throttling is useful in some cases, more often you’re looking for debouncing. Debouncing essentially groups your events together and keeps them from being fired too often. To use it in a Vue component, just wrap the function you want to call in lodash’s _.debounce function.

Disclaimer: Do not use debounce on rubber balls unless you wish for them to stop bouncing. Debounce has little to no effect on bowling balls.

MyComponent.vue

<template>
  <button @click="throttledMethod()">Click me as fast as you can!</button>
</template>

<script>
import _ from 'lodash'

export default {
  methods: {
    throttledMethod: _.debounce(() => {
      console.log('I only get fired once every two seconds, max!')
    }, 2000)
  }
}
</script>

Reference

✖ Clear

πŸ•΅ Search Results

πŸ”Ž Searching...