0

I am trying to setup a counter from a specific date using RxJS on an Angular 14 project, but the counter seems wrong. Milliseconds only change on the red spot, seconds are changing on the orange spot, but seconds should change at the blue spot, and milliseconds should countup on the orange and red spot combined. Am I correct?

enter image description here

What is my mistake in this code?

TS:

startTime = new Date("April 10, 2013 00:00:00").getTime();
elapsedTime = Date.now() - this.startTime;
count: Observable<number> | undefined;
    
this.count = interval()
  .pipe(map(count => count + this.elapsedTime)
  );
}

This is the placeholder:

{{ count | async }}

Thank you

p0mman
  • 78
  • 7

1 Answers1

1

The problem is that you are scheduling with interval a new notification every ms, but the app cant process and render each notification in 1m. That means that as time goes by, the difference between the notification count being process (your intended measure of elapsedTime) and the real elapsed time in ms gets bigger and bigger and thus the time seems to run slower.

The easiest way to prevent this is increase the interval time between emissions to avoid a backlog of notifications, and to calculate the elapsedTime against the startTime in each iteration.

this.count = interval(30).pipe(
  map(count => Date.now() - this.startTime)
);

cheers

akotech
  • 1,961
  • 2
  • 4
  • 10