Ishtiaque Khan
Ishtiaque Khan

Reputation: 1226

RxJS: debounceTime on Rx.Observable.interval is not working as expected

In the following line of code I am expecting the printing of here every 2 seconds. But nothing is being printed:

Rx.Observable.interval(1000).debounceTime(2000).subscribe(x => console.log('here'))

However in the following line of code, here is printed every 2 seconds, as expected:

Rx.Observable.interval(2000).debounceTime(1000).subscribe(x => console.log('here'))

In the first case I am expecting an event stream of 1 second period to be debounced to 2 seconds period. This does not seem to work.

And in the second case I am expecting an event stream of 2 seconds period to be debounced to 1 second period. This seems to work.

Why is the first case not working as expected? Is there something wrong in my expectation?

Upvotes: 1

Views: 1196

Answers (2)

ZahiC
ZahiC

Reputation: 14687

You may confuse debounce with throttle.

debounceTime

For every item, wait X ms until no other item is emitted, and only then emits the item.

Rx.Observable.interval(1000).debounceTime(2000).subscribe(x => console.log('here'))

All items are dropped since an item will always be emitted within 2000 ms.

throttleTime

Emits an item if no other items were emitted during the last X ms. Otherwise, the item is dropped.

Rx.Observable.interval(1000).throttleTime(2000).subscribe(x => console.log('here'))

Prints an item every 2000 ms.

Upvotes: 3

th3n3wguy
th3n3wguy

Reputation: 3737

The problem with your first case is that you are creating a new interval every second, but telling the observable to wait until 2 seconds have passed in order to pass the object through to the subscription. Since the interval value is less than the debounceTime value, your subscription will never "resolve".

Upvotes: 2

Related Questions