I am currently trying to make a 20 second timer like this:
this.timer = Observable.interval(1000).take(20).map((tick) => tick+1).subscribe((tick) => {
this.reverseTimer = 20-tick;
})
This is fine if I let the Observable reach 20 every time, but sometimes, I want to end the timer early. Right now, I can't stop the timer until it stops itself after 20 seconds.
Right now, I am hiding the timer in the display when I want it to stop, but I need it to be able to restart. If I try to restart the timer before 20 seconds, reverseTimer flickers between the new timer and old timer values because I haven't stopped the old timer.
I have tried this.timer.unsubscribe() but I get the error that unsubscribe does not exist for timer.
You should take a look to the Timer operator. You can create an Observable that emits a particular item after a given delay. You can easily create your countdown system.
In this example, I will create a timer and then stop it after 5 seconds.
const start = 20;
const source = Rx.Observable
.timer(1000, 1000)
.map(tick => start - tick)
.take(start + 1)
.subscribe(tick => console.log(tick));
setTimeout(() => {
//Stop the timer
source.unsubscribe();
}, 5000);
You can see the Working plunkr
If unsubscribe does not exist on the result you've received from your call to subscribe, you are likely using RxJS 4. In which case, you will have received an IDisposable instance and should call dispose to stop the timer:
this.timer.dispose();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With