timeout

signature: timeout(due: number, scheduler: Scheduler): Observable

Error if no value is emitted before specified duration

timeout - 图1

Examples

Example 1: Timeout after 2.5 seconds

( jsBin |
jsFiddle )

  1. import { of } from 'rxjs/observable/of';
  2. import { concatMap, timeout, catchError } from 'rxjs/operators';
  3. // simulate request
  4. function makeRequest(timeToDelay) {
  5. return of('Request Complete!').pipe(delay(timeToDelay));
  6. }
  7. of(4000, 3000, 2000)
  8. .pipe(
  9. concatMap(duration =>
  10. makeRequest(duration).pipe(
  11. timeout(2500),
  12. catchError(error => of(`Request timed out after: ${duration}`))
  13. )
  14. )
  15. )
  16. /*
  17. * "Request timed out after: 4000"
  18. * "Request timed out after: 3000"
  19. * "Request Complete!"
  20. */
  21. .subscribe(val => console.log(val));

Additional Resources


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