0

Need to run a timer from custom datetime(past or future). Ex: Jun 15 2021 15:45:31 GMT+0530", "Tue Jun 15 2021 15:45:32 GMT+0530" (seconds)

startTimer() {
    const dateTime =  new Date('2021-06-15T15:45:30');
    setInterval(() => {
      this.now = dateTime;
      this.startTimer();
    }, 1000);
  }

// timer is not working and it is in static. (Tue Jun 15 2021 15:45:31 GMT+0530)

component :

{{ now }}
pietrodito
  • 1,783
  • 15
  • 24
reegan29
  • 920
  • 1
  • 12
  • 30

2 Answers2

2

You need to alter the actual value of this.now...

let now = new Date('2021-06-15T15:45:30');

function startTimer() {
  setInterval(() => {
    now = new Date(now.getTime() + 1000);
    console.log(now)
  }, 1000);
}

startTimer();

Above is a simple vanillaJS version. Since you tagged momentjs you might also want to have a look at add.
Alternatively, since you are using angular, you have some nice options to work with timers using rxjs - like interval or timer.

zwif
  • 195
  • 3
  • 13
  • When I reset the time zone in mobile or windows, the time (now) is changed. How set static time zone to halt the change? – reegan29 Apr 13 '21 at 09:32
  • The javascript `Date` has several options to work with timezones... Check this out: https://stackoverflow.com/questions/439630/create-a-date-with-a-set-timezone-without-using-a-string-representation – zwif Apr 14 '21 at 07:35
1

The problem is that you set dateTime before you start the timer with setInterval() and then after 1 second the time is being set again to the same date. also you should't be calling this.startTimer(); from inside the setInterval().

Try this:

const now =  new Date('2021-06-15T15:45:30');

startTimer() {
    setInterval(() => {
      this.now.setSeconds(this.now.getSeconds() + 1)
    }, 1000);
}
Hila Grossbard
  • 521
  • 7
  • 20