debounceTime delays the values emitted by a source for the given due time. If within this time a new value arrives, the previous pending value is dropped and the timer is reset. In this way debounceTime keeps track of most recent value and emits that most recent value when the given due time is passed.

The operator works in the following way:

  1. when new value arrives schedule a new interval
  2. remember the value and discard old ones if exists
  3. when the interval ends, emit the value
  4. if new value comes before the interval ends, run step 1 again

USAGE

This operator is mostly used for events that can be triggered tens or even hundreds of times per second. The most common examples are DOM events such as scrolling, mouse movement, and keypress. When using debouceTime you only care about the final state. For example, current scroll position when a user stops scrolling, or a final text in a searchbox after a user stops typing in characters.

debounceTime waits for the time period mentioned and then calls the subscribe method.

e.g; debounceTime(1000) will wait for 1 second. It is implemented through pipes.

  1. First ====> declare a subject variable
import { debounceTime } from 'rxjs/operators';
subject = new Subject<string>();

2. Then, on keyup event (for example) , you should trigger the subject

 onKeyUp(): void {
        this.subject.next();
    }

3. Now, you can use the debounce function

 this.subject
      .pipe(debounceTime(200))
      .subscribe((value) => {
         // you write your business logic here
      }
      );

PS: Common scenarios for a debounce are resize, scroll, and keyup/keydown events. In addition, you should consider wrapping any interaction that triggers excessive calculations or API calls with a debounce.

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *