Using debounce in Vue.js templates

If you’ve ever used something like lodash, you may have heard of the debounce function. Debounce is useful for limiting the amount of calls a function makes in a set time frame (in milliseconds). For example, if you want to call a function once per second as a user is typing in a search box, debounce is a perfect use case. A common example is limiting API calls for something with rate limits such as google maps. When you type in a search box, you might have to listen to the change or onkeyup event which would call a function tens of times per second. You don’t want to query an API more times than you need to, so that’s where debounce comes in (among many other use cases).

How To Use Debounce Normally

From the lodash documentation:

jQuery(window).on('resize', _.debounce(calculateLayout, 150));
Call a function every 150 milliseconds from the last time it was called. This is useful on the resize event because it would normally call up to hundreds of times while a resize is in progress.

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)
}

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!

Comments