1

I am building a countdown timer in angular2 with timer observable (didnt find any other solution to this using angular2).

The timer starts at 15:00 minutes and goes down to 00:00. The problem which i am facing is that at first the timer is decreasing 1 second, but as the time pass to the seconds the gap increases.

In 14:00 -13:00 there comes the gap of 2-3 seconds compared with the timer running on stop watch on my phone. Gradually this seconds gap increases and till it reached 00:00 the difference is 3-4 minutes i.e timer is running for more than 15:00 minutes.

Also if I switch the tab the gap increases and it may take 30 minutes or 1 hr to countdown to 15:00 minutes.

import {Observable} from "rxjs/Rx";
import { Subscription } from "rxjs/Subscription";

public timer = Observable.timer(1000, 1000);
public startTime = 900;
  public timerfunction(): void {
           if ( this.counter < 10) {
           this.timerSubs = this.timer.subscribe((tt) => {
            //  console.log("inside timer" + this.counter);
             this.timerfunc(tt);
            });
           this.unsubscribeTimer();
          }
           this.counter = this.counter + 1;
  }
​public timerfunc(tt: number){
{ console.log("Timer ticks" + " : " + tt); 
  if (tt < this.startTime && tt !== 0) {
      if (tt % 60 === 0 && tt !== 0 && this.minutes !== 0) {
     // console.log("t" + tt + this.minutes + ":" + this.seconds );
     this.minutes = this.minutes - 1;
     this.seconds = 59;
    // console.log(this.startTime + "start time");
    }else {
     // console.log( "this.seconds ----- fucTTT" + this.seconds );
      if (this.seconds !== 0) {
      this.seconds = this.seconds - 1;
      } else if (this.seconds === 0 && this.minutes !== 0) {
        this.seconds = 59;
        this.minutes = this.minutes - 1 ;
      //  console.log("inside this loop");
      }
      // console.log("minutes" + this.minutes + "seconds" + this.seconds);
    }
  }}
Emmanuel
  • 4,933
  • 5
  • 46
  • 71
Sinha
  • 11
  • 3
  • The context of the question is clear, but please change the title and the ending of your post to actually *ask* a question. What do you want to know / get help with? – M. Mimpen Jun 29 '17 at 09:00
  • I want to know the solution of this problem . why this difference is happening?? – Sinha Jun 29 '17 at 11:37
  • try to do setTimeout(()=> {this.timerfunc(tt);}); to move the processing execution out of subscribe – Julia Passynkova Jun 29 '17 at 23:56

1 Answers1

0

Here is a simple implementation of a countdown timer:

import { interval } from 'rxjs'
import { map, take } from 'rxjs/operators'

const duration = 15 * 60 // 15 minutes

interval(1000).pipe(take(duration), map(count => duration - count)).subscribe(seconds => {
  console.log(seconds);
})
Emmanuel
  • 4,933
  • 5
  • 46
  • 71
  • Hi, can you answer it? https://stackoverflow.com/questions/70441794/swap-element-in-an-observable-array – anonymous Dec 21 '21 at 23:21