Demo: timer
The timer is like a superset of interval. With the first parameter specifying firstInterval and the second specifying the periodic intervals.
timer( firstInterval, periodcInterval)
The second parameter is optional, when not specifed the timer just emits once.
//emit every 1.5 sec, starting at 0.5 sec
let input = timer(500, 1500);
//let's take only the first 5 values
let process = take(5);
let output = input.pipe(process).subscribe(v=>console.log(v))
More on :
timer
1. timer vs interval
timer( firstInterval, optionlPeriodcInterval);
//---vs---//
interval(periodcInterval)
As seen above timer is a superset of interval where we can decide the first interval separately. For example,
- When the same first interval is same as the periodic interval, we can use interval instead.
//Start at 2 sec and continue with periodic intervals of 2 sec each.
timer(2000, 2000);
//Equivalent operator using -interval
interval(2000)
- timer : for the first interval which is different from the periodic intervals
//Start immediately and continues with periodic intervals of 2 sec each.
timer(0, 2000);
//Start at 1 sec and continue with periodic intervals of 2 sec each.
timer(1000, 2000);
- timer for a single emit and no periodic emits
//Emits only 0 at 2sec
timer(2000);
2. timer or interval - For perioic actions
We can use timer/interval for creating counters, stopwatch etc using it's emitted numbers.
Apart from it's numbers, we can use it's emission intervals for perioddic actions as below.
import {interval} from 'rxjs';
let getMarketData = () =>{
console.log('Fetching market data...');
}
//Get market data every minute
interval(60*1000)
.subscribe(() => {getMarketData();})
Output :
Fetching market data...
Fetching market data...
(repeats every 1 min.)