How can I use debounce
on an async
function? I have a method within my vue
-app which reveives data from an API which calls the API continuosly which I want to avoid.
Here is my method:
methods: {
async getAlbums () {
const response = await AlbumService.fetchAlbums()
this.albums = response.data.albums
}
}
I've installed lodash
previously so how can I achieve that?
all the two await calls can be started before either one is resolved. The answer is misleading. The jsbin code appears to be executing promises in parallel, but they are not.
The debounce() function forces a function to wait a certain amount of time before running again. The function is built to limit the number of times a function is called. The Send Request() function is debounced. Requests are sent only after fixed time intervals regardless of how many times the user presses the button.
The major difference between debouncing and throttling is that debounce calls a function when a user hasn't carried out an event in a specific amount of time, while throttle calls a function at intervals of a specified amount of time while the user is carrying out an event.
Lodash's debounce
function takes in a function , time to wait and returns a function.
So do it like this:
methods: {
getAlbums: _.debounce(async function() {
const response = await AlbumService.fetchAlbums();
this.albums = response.data.albums;
}, 1000);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With