How to use the timer function from rxjs

Find comprehensive JavaScript rxjs.timer code examples handpicked from public code repositorys.

rxjs.timer is a function that creates an observable that emits a sequence of numbers after a specified delay or at regular intervals, depending on the arguments provided.

8
9
10
11
12
13
14
15
16
17
retryWhen(error$ =>
    error$.pipe(
        mergeMap(
            error => {
                log.warn(`Reconnecting in ${delay}ms after error: ${error}`)
                return timer(delay)
            }
        )
    )
)
fork icon45
star icon178
watch icon34

130
131
132
133
134
135
136
137
138
139
        mergeMap(
            ([error, retry]) => {
                if (error.statusCode < 500 || retry > retries)
                    return throwError(() => error)
                else
                    return timer(Math.pow(2, retry) * 200)
            }
        )
    )
})
fork icon45
star icon178
watch icon34

How does rxjs.timer work?

Sure! rxjs.timer is a function that creates an Observable that will emit a sequence of numbers after a specified delay or at regular intervals, depending on the arguments provided. The function takes up to three arguments: the first argument is the initial delay (in milliseconds) before the first value is emitted, the second argument is the interval (in milliseconds) between subsequent emissions, and the third argument is the scheduler (which is optional and determines the execution context of the timer). If only the first argument is provided, the Observable will emit a single value after that delay. If both the first and second arguments are provided, the Observable will emit values at regular intervals starting after the initial delay. If only the second argument is provided, the Observable will emit values at regular intervals with no initial delay. The returned Observable will emit an infinite sequence of increasing integers starting from zero, unless the third argument is provided to use a different Scheduler, which determines the timing and execution context of the emissions.

11
12
13
14
15
16
17
18
19
const { zip, share, take } = require('rxjs/operators');


// our source will be a basic timer
// making 5 ticks, every 5ms
const source$ = timer(0, 5).pipe(
  take(5),
  zip(from(palette), Marble) // add color to items
);
fork icon10
star icon160
watch icon3

+ 13 other calls in file

28
29
30
31
32
33
34
35
36
37
const { rxObserver } = require('api/v0.3');
const { timer } = require('rxjs');
const { mapTo } = require('rxjs/operators');
const { query, some, mute } = require('rx-rql');

const a = timer(200).pipe(mapTo('a'));
const b = timer(0, 50).pipe(mapTo('b'));
const c = timer(800).pipe(mapTo('c'));

a.subscribe(rxObserver('a'));
fork icon10
star icon159
watch icon3

+ 11 other calls in file

Ai Example

1
2
3
4
5
6
const { timer } = require("rxjs");

const source = timer(1000, 2000);
const subscription = source.subscribe((value) => console.log(value));

// Output: 0 (after 1 second), 1 (after 3 seconds), 2 (after 5 seconds), and so on...

In this example, we first import timer from the rxjs library. We then create an Observable source using timer(1000, 2000), which emits the first value after 1 second and subsequent values at 2-second intervals. We subscribe to this Observable and log each emitted value to the console using subscription. After one second, the Observable emits the first value 0. After another two seconds, it emits the second value 1. This pattern continues indefinitely, with each subsequent value being emitted at 2-second intervals. Therefore, the console will log 0, 1, 2, and so on, until the subscription is terminated.

11
12
13
14
15
16
17
18
19
20
const {rxObserver} = require('api/v0.3');
const { timer } = require('rxjs');
const { map, tap, retryWhen, delayWhen } = require('rxjs/operators');

const source$ =
  timer(0, 100).pipe(
    map(val => {
      if (val == 1) {
        throw 'Err';
      }
fork icon10
star icon159
watch icon3

+ 7 other calls in file

123
124
125
126
127
128
129
130
131
132

let lastResourcesState = resources; // the last state we had recorded

const timeoutError$ =
  timeout !== Infinity
    ? timer(timeout).pipe(
        mergeMap(() => {
          const resourcesWaitingFor = determineRemainingResources(resources, lastResourcesState).join(', ');
          return throwError(Error(`${TIMEOUT_ERR_MSG}: ${resourcesWaitingFor}`));
        })
fork icon85
star icon0
watch icon0

+ 15 other calls in file

29
30
31
32
33
34
35
36
37
38
})

unlock$.pipe(
    tap(instance => instance.locked = false),
    mergeMap(instance =>
        timer(maxIdleMilliseconds).pipe(
            takeUntil(lock$.pipe(
                filter(currentInstance => currentInstance === instance)
            )),
            map(() => instance)
fork icon45
star icon178
watch icon34

85
86
87
88
89
90
91
92
93
94

  return of('');
}),

concatMap(() => {
  return timer(UPDATE_TIMEOUT).pipe(
    tap({ next: () => {
        if (checkerSubject) {
          try {
            checkerSubject.next();
fork icon77
star icon162
watch icon0

48
49
50
51
52
53
54
55
56
57
    }
    return EMPTY
}

const poll$ =
    timer(0, pollIntervalMilliseconds).pipe(
        takeWhile(() => state.enabled)
    )

trigger$.pipe(
fork icon45
star icon177
watch icon0

10
11
12
13
14
15
16
17
18
19
```js
const { rxObserver } = require('api/v0.3');
const { timer } = require('rxjs');
const { takeUntil } = require('rxjs/operators');

const source$ = timer(0, 100);
const terminator$ = timer(550);

source$.subscribe(rxObserver('source$'));
terminator$.subscribe(rxObserver('terminator$'));
fork icon10
star icon159
watch icon3

+ 3 other calls in file

15
16
17
18
19
20
21
22
23
24
const { finalize, tap } = require('rxjs/operators');

// you'll need to open console
// for this example

const sub = timer(10)
  .pipe(
    finalize(()=>
      console.log(`Finished @ ${ Date.now() }ms`)
    ),
fork icon10
star icon159
watch icon3

15
16
17
18
19
20
21
22
23
24
const T = 5;

of(1).pipe(
    expand(value =>
      value < T
      ? timer(T, T).pipe(
          take(value + 1),
          mapTo(value + 1)
       )
      : EMPTY
fork icon10
star icon159
watch icon3

26
27
28
29
30
31
32
33
34
35
      )
  );

// visualization
source$.subscribe(rxObserver('source$'));
exhaustMap$.subscribe(rxObserver('exhaustMap( timer(0, 3).take(3) )'));


// helpers
function colorize(color) {
fork icon10
star icon159
watch icon3

+ 3 other calls in file

62
63
64
65
66
67
68
69
70
71
exports.pairs = rxjs.pairs;
exports.partition = rxjs.partition;
exports.race = rxjs.race;
exports.range = rxjs.range;
exports.throwError = rxjs.throwError;
exports.timer = rxjs.timer;
exports.using = rxjs.using;
exports.zip = rxjs.zip;
exports.scheduled = rxjs.scheduled;
exports.EMPTY = rxjs.EMPTY;
fork icon299
star icon0
watch icon1

11
12
13
14
15
16
17
18
19
20
const { expand, mapTo } = require('rxjs/operators');

of(1).pipe(
    expand(value =>
      value < 5
      ? timer(5).pipe(mapTo(++value))
      : EMPTY
    )
  )
  .subscribe(rxObserver());
fork icon10
star icon0
watch icon1

18
19
20
21
22
23
24
25
26
27
const source$ = fromDelayed([ 5, 10, 20 ]).pipe(
    zip(from(palette), Marble) // colorize each item
  );

// target$ that we'll be mapping to
const target$ = timer(0, 3).pipe(take(3));

const mergeMap$ = source$.pipe(
    mergeMap(x => target$.pipe(colorize(x.color))) // colorize as source$ value
  );
fork icon10
star icon0
watch icon1

11
12
13
14
15
16
17
18
19
const { rxObserver } = require('api/v0.3');
const { timer, race } = require('rxjs');
const { mapTo, take } = require('rxjs/operators');


const a$ = timer(10).pipe(mapTo('a'));
const b$ = timer(5, 5).pipe(take(3));

const result$ = race([ a$, b$ ]);
fork icon10
star icon0
watch icon1

+ 7 other calls in file

38
39
40
41
42
43
44
45
46
47
      console.log(
        `Attempt ${retryAttempt}: retrying in ${retryAttempt *
          scalingDuration}ms`
      );
      // retry after 1s, 2s, etc...
      return timer(retryAttempt * scalingDuration);
    }),
    finalize(() => console.log('We are done!'))
  );
};
fork icon6
star icon12
watch icon3

+ 3 other calls in file

37
38
39
40
41
42
43
44
45

const mergeHeartbeat = (heartbeatDelay, heartbeatValue) =>
    observable$ =>
        merge(
            observable$,
            timer(heartbeatDelay, heartbeatDelay).pipe(
                mapTo(heartbeatValue)
            )
        )
fork icon5
star icon12
watch icon8

+ 3 other calls in file

-1
fork icon3
star icon6
watch icon4

+ 20 other calls in file