Ole
Ole

Reputation: 47172

Understanding RxJS debounce semantics

From this article:

 const debouncedInput = example.debounceTime(5);

 const subscribe = debouncedInput.subscribe(val => {
   console.log(`Debounced Input: ${val}`);
 });

After the first keyup will the debouncedInput wait to call the observer for 5 milliseconds?

Also suppose the user keeps typing before the 5 millisecond interval expires. Does the debouncedInput Observable wait until an uninterrupted 5 millisecond period passes before publishing the event / source value?

In terms of an example (Per the very helpful marble diagram in @OJKwon s answer) suppose the - represents a millisecond. And we have the following:

 -a--b--c-------d

In this case the timer that monitors the interval will be restarted at:

Upvotes: 1

Views: 90

Answers (1)

OJ Kwon
OJ Kwon

Reputation: 4651

What the debounceTime operator does is delay the source observable emission by the specified timeframe. If another source value is emitted during the delay it:

  • Drops previous value
  • Resets the interval timer
  • Wait to see whether the interval will pass without more source values being emitted.
  • Finally if the are no values emitted during the interval it will emit the last value.

RxJSs marble test diagram illustrates this quite well. Lets review a few cases.

When we have source.debountTime(20),

  1. all source value emission occurs after 20

const source = '-a--------b------'; const expected = '---a--------b----';

all of source values are just simply delayed.

  1. if some source value emitted subsequently in 20ms

const source = '-a--bc--d---|'; const expected = '---a---c--d-|';

emitted a delayed by 20ms, b dropped since c emitted before timespan of 20ms for next emission, then d is delayed by 20ms after c does.

To summarize the debounceTime operator functions as a rate limiter only allowing a single value to be emitted in given timeframe.

Upvotes: 2

Related Questions