Demo: throttle
After every emit, the time-interval filter throttle, discards the source items until the inner observable emits a value.
throttle is similar to throttleTime.
Instead of the time in milliseconds as in throttleTime, throttle uses the specified innerObservable to decide on the time interval.
throttle(v=>timer(2000))
//Each item is delayed by v*100 milliseconds
let source = of(2,8,15,25,4,45,5,6)
.pipe(concatMap(v=>of(v).pipe(delay(100*v))));
//ignore the inputs for next 2 secs after every emit
let timeIntervalFilter = throttle(v => timer(2000));
let output = source.pipe(timeIntervalFilter).subscribe(v=>console.log(v))
What is happening ?
After every emit, the time-interval filter throttle: discards the source items until the inner observable emits a value.
The audit is a time-interval filter, very similar to auditTime.
Let's understand how it works with the demo. Let's start with the first item 2 from the source.
- As soon as the value 2 arrives the "throttle Time" filter immediately emits it.
- It, also, starts the inner observable, the 2 second timer and discards all source items until the timer emits.
- Thus, it discards 8 as it falls within the 2 second timer interval.
- 15 comes after 8+15=23 or 2.3 seconds after 2, falling beyond the first throttle interval. Now, the filter starts the throttle cycle again for 15.
- But, discards nothing as the next value arrives only after 2.5 seconds. Again, the filter starts it's next cycle with 25 discarding 4. Importantly, the last throttle time cycle starts with 45.
- 2 source items 5 and 6 arrives within this cycle, hence the filter discards both of them. Now analyzing the output here, since the throttle emits the first value without any delay:
- It's a good choice, if all our source items are similar and we are just limiting the rate.
- But, in case the latest value is important to us, then this filter is not the right choice.
- The "audit Time" or the "debounce Time" could be the right alternatives here.