Home > Net >  Using an interval and calculating a dateTime countdown is killing my CPU in Google Chrome
Using an interval and calculating a dateTime countdown is killing my CPU in Google Chrome

Time:10-06

I'm showing a date/time countdown on the screen with my Angular app. It's a countdown from a specific date and time.

Running it every second is killing my CPU with Google Chrome. It might be the moment() lib that has some effect, but not sure yet. I might try it without moment, to see if that helps. enter image description here

Is there a better (more efficient) way to do this?

Here is my code

calculateTimeRemaining(endDate: Date, timeZone: string, eventId: number) {
  setInterval(() => {
    const element = document.getElementById("event-"   eventId);
    if (element) {
      const currentDateUtc = moment().utc();
      const endDateUtc = moment(endDate).utc(true);
      endDateUtc.tz(timeZone);
      const dif = moment.duration(endDateUtc.diff(currentDateUtc));
      const hours = dif.hours();
      const minutes = dif.minutes();
      const seconds = dif.seconds();
      if (hours < 1) {
        element.innerHTML = minutes   ' m '   seconds   ' s';
      } else {
        element.innerHTML = hours   ' h '   minutes   ' m '   seconds   ' s';
      }
    }
  }, 1000);
}
<span id="event-{{event.id}}" class="float-right yb-color">{{calculateTimeRemaining(event.datePendingUtc, event.yogabandTimeZoneId, event.id)}}</span>

CodePudding user response:

For performance, don't call any function inside Angular template because it will run in every change detection.

This article describes the issue very well https://medium.com/showpad-engineering/why-you-should-never-use-function-calls-in-angular-template-expressions-e1a50f9c0496

We could change your implementation using pure pipe

time-remaining.pipe.ts

@Pipe({
  name: 'timeRemaining',
})
export class TimeRemainingPipe {
  transform(event: any): any {
    // put implementation here
    // return time remaining
  }
}

I believe in the pipe, you could remove const element = document.getElementById("event-" eventId); part.

component.html

<span id="event-{{event.id}}" class="float-right yb-color">{{ event | timeRemaining }}</span>

Reference: https://angular.io/guide/pipes

  • Related