我正在使用 Angular 應用程式在螢屏上顯示日期/時間倒計時。這是從特定日期和時間開始的倒計時。
每秒運行一次都會用 Google Chrome 殺死我的 CPU。可能是 moment() 庫有一些影響,但還不確定。我可能會立即嘗試,看看是否有幫助。

有沒有更好(更有效)的方法來做到這一點?
這是我的代碼
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>
編輯(解決方案) - 我已經在管道中實作了一個倒數計時器(按照推薦)來解決這個問題。我將包括下面管道的完整代碼以及我如何稱呼它。我還有一個服務,用于在計時器到時向我的組件發送通知,以便我可以執行其他操作。
import { Pipe, PipeTransform } from '@angular/core';
import { Observable, of, timer } from 'rxjs';
import { map, takeWhile } from 'rxjs/operators';
import { EventService } from 'src/app/core/services/event.service';
@Pipe({
name: 'timeRemaining'
})
export class TimeRemainingPipe implements PipeTransform {
eventId: number;
expired = false;
constructor(private eventService: EventService) {}
/**
* @param futureDate should be in a valid Date Time format
* e.g. YYYY-MM-DDTHH:mm:ss.msz
* e.g. 2021-10-06T17:27:10.740z
*/
public transform(futureDateUtc: string, eventId: number): Observable<string> {
this.eventId = eventId;
/**
* Initial check to see if time remaining is in the future
* If not, don't bother creating an observable
*/
if (!futureDateUtc || this.getMsDiff(futureDateUtc) < 0) {
console.info('Pipe - Time Expired Event: ' eventId);
return of('EXPIRED');
}
return timer(0, 1000).pipe(
takeWhile(() => !this.expired),
map(() => {
return this.msToTime(this.getMsDiff(futureDateUtc));
})
);
}
/**
* Gets the millisecond difference between a future date and now
* @private
* @param futureDateUtc: string
* @returns number milliseconds remaining
*/
// Z converts to local time
private getMsDiff = (futureDate: string): number => ( (new Date(futureDate 'Z')) - Date.now());
/**
* Converts milliseconds to the
*
* @private
* @param msRemaining
* @returns null when no time is remaining
* string in the format `HH:mm:ss`
*/
private msToTime(msRemaining: number): string | null {
if (msRemaining < 0) {
console.info('Pipe - No Time Remaining:', msRemaining);
this.expired = true;
this.eventService.expired(this.eventId);
return 'EXPIRED';
}
let seconds: string | number = Math.floor((msRemaining / 1000) % 60),
minutes: string | number = Math.floor((msRemaining / (1000 * 60)) % 60),
hours: string | number = Math.floor((msRemaining / (1000 * 60 * 60)) % 24);
/**
* Add the relevant `0` prefix if any of the numbers are less than 10
* i.e. 5 -> 05
*/
seconds = (seconds < 10) ? '0' seconds : seconds;
minutes = (minutes < 10) ? '0' minutes : minutes;
hours = (hours < 10) ? '0' hours : hours;
return `${hours}:${minutes}:${seconds}`;
}
}
<span class="float-right yb-color">{{(event.dateUtc | timeRemaining: event.id | async}}</span>
這里是服務
export class EventService {
private subject = new Subject <any> ();
expired(eventId: number) {
this.subject.next(eventId);
}
expiredEvents(): Observable <any> {
return this.subject.asObservable();
}
}
// how it's called in the component
this.eventService.expiredEvents().subscribe(eventId => {
console.info('Service - Expired Event:', eventId);
// do something now w/ expired event
});
uj5u.com熱心網友回復:
為了性能,不要在 Angular 模板中呼叫任何函式,因為它會在每次更改檢測中運行。
這篇文章很好地描述了這個問題https://medium.com/showpad-engineering/why-you-should-never-use-function-calls-in-angular-template-expressions-e1a50f9c0496
我們可以使用純管道更改您的實作
time-remaining.pipe.ts
@Pipe({
name: 'timeRemaining',
})
export class TimeRemainingPipe {
transform(event: any): any {
// put implementation here
// return time remaining
}
}
我相信管道,你可以移除const element = document.getElementById("event-" eventId);一部分。
component.html
<span id="event-{{event.id}}" class="float-right yb-color">{{ event | timeRemaining }}</span>
參考:https : //angular.io/guide/pipes
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/314097.html
標籤:javascript 有角的 表现 瞬间 设置间隔
