Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use debounce on async function? [duplicate]

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?

like image 489
ST80 Avatar asked Jun 13 '18 12:06

ST80


People also ask

Can one Async have two awaits?

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.

How do you use debounce function?

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.

What is the difference between Debounce and throttle?

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.


1 Answers

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);
}
like image 158
Vamsi Krishna Avatar answered Sep 19 '22 17:09

Vamsi Krishna