Skip to content

counter

Creates an observable that emits incremental numbers at a specified interval. Emits 0 in the macrotask right after start() (which runs at creation unless startManually is set), then 1, 2, 3, … every interval. A subscriber added after that 0 has been emitted does not receive it.

  • startManually (default false): wait for start() instead of starting at creation.
  • emitInitial (default true): set to false to skip the 0 emitted right after start(), so the first value is 1, one interval later. counter(ms) corresponds to RxJS timer(0, ms); counter(ms, { emitInitial: false }) corresponds to interval(ms).
// Timeline:
//
// Time(s) 0 1 2 3 4 5
// tick$ 0 1 2 3 4 5 ...
//
// Explanation:
// - counter emits incrementing numbers at specified intervals
// - Starts at 0 and continues indefinitely
// - Useful for periodic tasks or animations
const tick$ = counter(100);
const valueHistory: number[] = [];
const subscription = tick$.subscribe((count) => {
valueHistory.push(count);
});
await new Promise((resolve) => {
setTimeout(resolve, 350);
});
subscription.unsubscribe();
assert.isTrue(Arr.isMinLengthArray(3, valueHistory));
assert.strictEqual(valueHistory[0], 0);
assert.strictEqual(valueHistory[1], 1);
assert.strictEqual(valueHistory[2], 2);

View source on GitHub