throttle

signature: throttle(durationSelector: function(value): Observable | Promise): Observable

Emit value only when duration, determined by provided function, has passed.

throttle - 图1

Examples

Example 1: Throttle for 2 seconds, based on second observable

( jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { throttle } from 'rxjs/operators';
  3. //emit value every 1 second
  4. const source = interval(1000);
  5. //throttle for 2 seconds, emit latest value
  6. const example = source.pipe(throttle(val => interval(2000)));
  7. //output: 0...3...6...9
  8. const subscribe = example.subscribe(val => console.log(val));
Example 2: Throttle with promise

( jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { throttle, map } from 'rxjs/operators';
  3. //emit value every 1 second
  4. const source = interval(1000);
  5. //incrementally increase the time to resolve based on source
  6. const promise = val =>
  7. new Promise(resolve =>
  8. setTimeout(() => resolve(`Resolved: ${val}`), val * 100)
  9. );
  10. //when promise resolves emit item from source
  11. const example = source
  12. .pipe(
  13. throttle(promise),
  14. map(val => `Throttled off Promise: ${val}`);
  15. );
  16. const subscribe = example.subscribe(val => console.log(val));

Additional Resources


:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/throttle.ts