I try to implement a countdown timer in angular 6 using rxjs 6. I also need to be able to subscribe to results and to reset the timer:
What I tried:
var timer = interval(1000).pipe(
take(4)
);
timer.subscribe(x => console.log(x));
Result:
0
1
2
3
What I need is to reverse the timer to count from 3 to 1
I found this coundown function to implement reverse count, but I cannot subscribe to it, like in first example
interval(1000).pipe(
map((x) => { console.log( x) })
);
Result:
empty
I try to implement a countdown timer in angular 6 using rxjs 6. I also need to be able to subscribe to results and to reset the timer:
What I tried:
var timer = interval(1000).pipe(
take(4)
);
timer.subscribe(x => console.log(x));
Result:
0
1
2
3
What I need is to reverse the timer to count from 3 to 1
I found this coundown function to implement reverse count, but I cannot subscribe to it, like in first example
interval(1000).pipe(
map((x) => { console.log( x) })
);
Result:
empty
Share Improve this question asked Apr 9, 2019 at 9:24 AlexFF1AlexFF1 1,2934 gold badges25 silver badges47 bronze badges3 Answers
Reset to default 4You can use timer instead of interval, to actually implement the countdown you should map the timer result like this: map(i => countdownStart - i)
const countdownStart = 3;
Rx.Observable
.timer(1000, 1000)
.map(i => countdownStart - i)
.take(countdownStart + 1)
.subscribe(i => console.log(i));
Logs: 3 2 1 0
Another possible solution is to use the range operator.
Rx.Observable
.range(0, countdownStart + 1)
.map(i => countdownStart - i)
.subscribe(i => console.log(i));
Logs: 3 2 1 0
Here is how I do it with TimerObservable
. Remember to unsubscribe on destroy.
import {TimerObservable} from "rxjs/observable/TimerObservable";
import { Subscription } from 'rxjs';
export class MyComponent implements OnInit, OnDestroy {
private sub: Subscription;
ngOnInit() {
// Delay 0 seconds, run every second
let timer = TimerObservable.create(0, 1000);
let number = 3;
this.sub = timer.subscribe(t => {
if(number !== 0) {
console.log(number);
number--;
}
});
}
ngOnDestroy(): void {
this.sub.unsubscribe();
}
}
How about?
var timer = interval(1000).pipe(
take(4),
map(x => 3 - x)
);
timer.subscribe(console.log);