Angular click debounce

Kamil Kiełczewski picture Kamil Kiełczewski · Nov 15, 2018 · Viewed 10.7k times · Source

In my template I have a field and two buttons:

<div class="btn-plus" (click)="add(1)"> - </div>
<div class="txt"> {{ myValue }} </div>
<div class="btn-minus" (click)="add(-1)"> + </div>

In my component .ts file I have:

add(num) {
    this.myValue +=num;
    this.update(); // async function which will send PUT request
}

The this.update() function puts myValue in the proper field in a big JSON object and sends it to a server.

Problem: When a user clicks 10x in a short period of time on button plus/minus, then a request will be send 10 times. But I want to send a request only once - 0.5 sec after last click. How to do it?

Answer

user4676340 picture user4676340 · Nov 15, 2018

Use the takeUntil operator :

export class AppComponent  {
  name = 'Angular';

  calls = new Subject();

  service = {
    getData: () => of({ id: 1 }).pipe(delay(500)),
  };

  click() {
    this.calls.next(true);
    this.service.getData().pipe(
      takeUntil(this.calls),
    ).subscribe(res => console.log(res));
  }
}

Stackblitz (open your console to check the logs)