Skip to content

Function: timer()

timer(delayMs?, intervalMs?): Stream<number>

Defined in: streams/timer.ts:15

Creates a timer stream that emits numbers starting from 0.

This stream is useful for scheduling events or generating periodic data. It is analogous to setInterval but as an asynchronous stream.

Parameters

delayMs?

number = 0

The time in milliseconds to wait before emitting the first value (0). If 0, the first value is emitted immediately (in the next microtask).

intervalMs?

number

The time in milliseconds between subsequent emissions. If not provided, it defaults to delayMs.

Returns

Stream<number>

A stream that emits incrementing numbers (0, 1, 2, ...).

Examples

From timer.spec.ts:4

typescript
const intervalMs = 100;
const timerStream = timer(0, intervalMs);
const emittedValues: number[] = [];
const subscription = timerStream.subscribe({
  next: (value) => emittedValues.push(value),
  complete: () => {
    // Check that values are emitted at the correct interval
    expect(emittedValues.length).toBeGreaterThan(1); // At least two emissions should be received
    for (let i = 1; i < emittedValues.length; i++) {
      expect(emittedValues[i] - emittedValues[i - 1]).toBe(1); // Values should increment by 1, indicating interval passes
    }

    done();
  },
});
setTimeout(() => {
  subscription.unsubscribe();
}, 250);

Released under the MIT License.