BACK
Lessons12. interval and take
Lessons · 12

12. interval and take

interval — an infinite timer

interval(period) starts "ticking" after the given period. First it waits period milliseconds, then emits 0, waits another period ms — emits 1, and so on. On its own it never completes.

interval(10)
// 10ms → 0 → 10ms → 1 → 10ms → 2 → ... (forever)

Your first "helper operator" — take

To rein in a stream like that safely, there's the take(N) operator. It lets the first N values through and then completes the stream immediately via complete.

interval(10).pipe(take(3))
// 10ms → 0 → 10ms → 1 → 10ms → 2 → complete()

Glossary

  • pipe(...) — an Observable method that runs a stream through a chain of operators. Each operator can filter, transform, or limit the values.
  • Operator — a function that takes an Observable and returns a new Observable with changed behavior. take is our first one.

Heads up

An unbounded interval is a common cause of leaks. In real apps it's almost always followed by take, takeUntil, or some other way to stop it.

Your task

  1. Inside interval(10).pipe(...), add take(3).
  2. That limits the stream to the first three values: 0, 1, 2.
  3. The marble check expects exactly that behavior.

Deterministic check

This task's check runs in TestScheduler virtual time. If your solution is right, the console shows only Test Passed!. Don't add extra console.logs, or the check will fail.

Solution spoiler · click to reveal
const { interval, take } = Rx;

const ticks$ = interval(10).pipe(
  take(3)
);
script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...