gpt4 book ai didi

javascript - 计时器 - Angular 8 的计时器

转载 作者:行者123 更新时间:2023-12-01 00:03:00 26 4
gpt4 key购买 nike

我正在尝试显示一个计时器,如下面的屏幕截图所示。不断计数以显示自输入此条目以来已有多长时间。

enter image description here

我找不到太多在 Angular 中执行此操作的选项。我在 Angular JS 中找到了这个解决方案。 https://siddii.github.io/angular-timer/我需要这样的计时器。但我无法将其移植到 Angular 中,或者说我不能。因此尝试了其他可用的替代方案,发现这些仍然不起作用。

https://www.npmjs.com/package/ng2-simple-timer

https://www.npmjs.com/package/ngx-timer

我最接近的是这个 ngx-timer 的 Countup-timer。 https://www.npmjs.com/package/ngx-timer计时器工作正常,并且能够根据我的要求从给定日期开始。开始计时器(开始日期)。但它有一个尚未解决的已知问题,即它会将自身应用于计时器元素的最后一个已知索引,从而在整个计时器列表中只有一个计时器运行。您可以在上面给出的屏幕截图中注意到这一点。

这是一个已知的错误。 https://github.com/Y4SHVINE/ngx-timer-lib/issues

有人可以帮助我找到一个解决方案或对其中一个解决方案进行一些调整以使其发挥作用吗?

谢谢。

最佳答案

我将通过编写一个函数来返回当前时间和对象创建时间之间的差异来实现此目的。

我最初的想法是将差异作为 Date 对象返回,然后格式化结果。在格式化不同的时间跨度时,我很快就遇到了问题,因为日期与时间跨度不同。

因此,我不会尝试格式化假装为时间跨度的Date,而是创建自己的界面。

export interface TimeSpan {
hours: number;
minutes: number;
seconds: number;
}

通过这样做,我们保留了对如何处理 >= 1 天的时间跨度的控制,并避免时区问题。

我将使用 OnPush 更改检测来控制更改检测的运行时间:

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
constructor(private changeDetector: ChangeDetectorRef) {}
}

然后我会在 ngOnInit() 中启动 RxJS interval,确保在完成后取消订阅:

private destroyed$ = new Subject();

ngOnInit() {
interval(1000).subscribe(() => {
this.changeDetector.detectChanges();
});
}

ngOnDestroy() {
this.destroyed$.next();
this.destroyed$.complete();
}

然后 HTML 将从我的组件上的函数获取耗时:

getElapsedTime(entry: Entry): TimeSpan {        
let totalSeconds = Math.floor((new Date().getTime() - entry.created.getTime()) / 1000);

let hours = 0;
let minutes = 0;
let seconds = 0;

if (totalSeconds >= 3600) {
hours = Math.floor(totalSeconds / 3600);
totalSeconds -= 3600 * hours;
}

if (totalSeconds >= 60) {
minutes = Math.floor(totalSeconds / 60);
totalSeconds -= 60 * minutes;
}

seconds = totalSeconds;

return {
hours: hours,
minutes: minutes,
seconds: seconds
};
}

此函数首先获取自创建日期以来经过的总秒数,然后计算出小时、分钟和秒部分。

其中 entry 是包含一些指示其创建时间的 Date 实例的对象。对于我的演示,我使用这个界面:

export interface Entry {
created: Date;
id: string;
}

然后可以检索 *ngFor 内每个实例的耗时跨度,如下所示:

<span *ngIf="getElapsedTime(entry) as elapsed">
{{elapsed.hours}} h {{elapsed.minutes}} m {{elapsed.seconds}} s
</span>

演示:https://stackblitz.com/edit/angular-p1b9af

关于javascript - 计时器 - Angular 8 的计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60586930/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com