What does timer() do?
timer() in RxJS creates a stream (Observable) that emits a value after a delay,
and if needed, it can also repeat at an interval.
Simple version:
ts
import { timer } from 'rxjs';
timer(2000).subscribe(() => console.log('2 seconds have passed'));Outputs the message once, after 2 seconds.
Repeating version:
ts
timer(1000, 2000).subscribe(x => console.log(x));- After 1 second it outputs
0, - then every 2 seconds:
1,2,3...
This is like interval(), but with an initial delay.
Comparison:
| What it does | What it looks like |
|---|---|
| One-time run after 3 sec | timer(3000) |
| Starts after 1 sec, then every 2 | timer(1000, 2000) |
Where it's used:
- Show a message after a delay
- Start a countdown after a pause
- Simulate loading
- Combine with
switchMapto start a timer after a click
Conclusion:
timer() is a reactive "delay".
You can run something after a time or regularly, with precise control over pauses.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.