Luke Curtis

Luke Curtis

Software Developer and Project Manager

Contact Me

Debounce in Vue with Lodash

18/02/2019 (1 month ago) | Luke Curtis

Using debounce is a super easy way of making sure you're not hammering your endpoints with resource intensive tasks.

Have you ever noticed how sometimes websites will automatically update a page without needing to refresh, or you click save? Usually what's happening, at least in Vue land is an event handler for this action. So, for example with the following code:

Our basic update method

Our basic update method

So here we have a list of inputs where we have a users email address for example, and every time we type in the input we want to update their email address. In this instance I'm just logging it but you might want to make an Axios call for example.

You can see how this would be intensive, every single time I type a letter or change something, it's going to go to our API or external provider and attempt to update that data.

This is where debounce comes in. Its a beautiful function for rate limiting your requests. The way you would do such a thing, in Lodash is something like the following

Our throttled debounce method

Our throttled debounce method

You'll notice here we use a closure syntax after lodash's debounce and call a patch request with the final parameter being 2000 which is the rate in milliseconds we want to throttle this request by.

By doing this, we now can guarantee that, within 60 seconds for example, we will make a maximum of 30 requests to our API, therefore making it a lot more efficient and a lot less resource intensive.

See the gist here