Angular2 Observable Timer Condition

Milo picture Milo · May 3, 2017 · Viewed 31.6k times · Source

I have a timer:

initiateTimer() {
    if (this.timerSub)
        this.destroyTimer();

    let timer = TimerObservable.create(0, 1000);
    this.timerSub = timer.subscribe(t => {
        this.secondTicks = t
    });
}

How would I add the condition to after 60 minutes present a popup to the user? I've tried looking at a couple of questions (this and this) but it's not clicking for me. Still new to RxJS patterns...

Answer

Will picture Will · May 3, 2017

You don't need RxJS for that. You can use good old setTimeout:

initiateTimer() {
    if (this.timer) {
        clearTimeout(this.timer);
    }

    this.timer = setTimeout(this.showPopup.bind(this), 60 * 60 * 1000);
}

If you really must use RxJS, you could:

initiateTimer() {
    if (this.timerSub) {
        this.timerSub.unsubscribe();
    }

    this.timerSub = Rx.Observable.timer(60 * 60 * 1000)
        .take(1)
        .subscribe(this.showPopup.bind(this));
}