timer

signature: timer(initialDelay: number | Date, period: number, scheduler: Scheduler): Observable

After given duration, emit numbers in sequence every specified duration.

timer - 图1

Examples

Example 1: timer emits 1 value then completes

( jsBin |
jsFiddle )

  1. import { timer } from 'rxjs/observable/timer';
  2. //emit 0 after 1 second then complete, since no second argument is supplied
  3. const source = timer(1000);
  4. //output: 0
  5. const subscribe = source.subscribe(val => console.log(val));
Example 2: timer emits after 1 second, then every 2 seconds

( jsBin |
jsFiddle )

  1. import { timer } from 'rxjs/observable/timer';
  2. /*
  3. timer takes a second argument, how often to emit subsequent values
  4. in this case we will emit first value after 1 second and subsequent
  5. values every 2 seconds after
  6. */
  7. const source = timer(1000, 2000);
  8. //output: 0,1,2,3,4,5......
  9. const subscribe = source.subscribe(val => console.log(val));

Additional Resources


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