Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Observable Timer Condition

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...

like image 809
Milo Avatar asked May 03 '17 14:05

Milo


2 Answers

I ended up doing this from what I initially had which gives me what I need:

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

    let timer = TimerObservable.create(0, 1000);
    let hour = 3600;
    this.timerSub = timer.subscribe(t => {
        this.secondTicks = t;
        if (this.secondTicks > hour) {
            alert("Save your work!");
            hour = hour * 2;
        }
    });
}

I implemented this before I tried what I marked as answer, so will just leave it here.

like image 91
Milo Avatar answered Sep 28 '22 03:09

Milo


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));
}
like image 28
Will Avatar answered Sep 28 '22 02:09

Will