首页 > 解决方案 > 每个人都完全相同的倒计时计时器 hh:mm:ss

问题描述

我正在为拍卖网站使用角度,使用时刻和显示计数器计算拍卖结束时间的剩余时间,但是当用户更改他的时钟时间时它会失败。

从服务器获取准确的时间并计算剩余时间很好,但是在页面加载后,时钟创建问题令人不安,有没有办法获取系统时钟更改事件或检查用户是否设置了自动同步/互联网时间?

虽然从服务器获取剩余时间还包括网络响应延迟和其他一些问题,但需要知道为每个人显示完全相同的计时器的最佳方法。

标签: angularcountdowntimerangular-moment

解决方案


您可以尝试订阅文档焦点,然后从服务器获取日期时间。在发现客户日期和价值之间的差异之后。有些喜欢

  inc: number = 0;
  timeInitial = 0;
  time;
  toogle: boolean = false;
  constructor(private timerService: TimerService) {}
  click() {
    this.toogle = !this.toogle;
    if (this.toogle) {
      fromEvent(document, "focus")
        .pipe(
          takeWhile(() => this.toogle),
          startWith(null),
          switchMap(() => {
            return this.timerService.getTime();
          })
        )
        .subscribe(res => {
          this.inc = new Date().getTime() - res.time;
          if (!this.timeInitial) this.timeInitial = res.timeInitial;
          console.log(this.inc, this.timeInitial);
        });

      timer(0, 1000)
        .pipe(
          takeWhile(() => this.toogle),
          map(() => {
            return (
              this.timeInitial -
              new Date(new Date().getTime() - this.inc).getTime()
            );
          })
        )
        .subscribe(res => {
          this.time = res;
        });
    } else {
      this.timeInitial = 0;
    }
  }

您的 .html 为

<button (click)="click()">{{toogle?'stop':'start'}}</button>
{{time |date:'H:mm:ss':'UTC'}}

以及我们的服务,它调用给我们日期时间的服务器,例如

export class TimerService {
  constructor(private httpClient: HttpClient) {}
  getTime() {
    return this.httpClient
      .get("https://worldtimeapi.org/api/timezone/America/Argentina/Salta")
      .pipe(
        map((res: any) => {
          const time = new Date(res.datetime).getTime();
          return {
            time: time,
            timeInitial: time + 30 * 60 * 1000
          };
        })
      );
  }
}

好吧,如果您更改计算机中的时间,您会看到倒计时发生变化,但是当您关注应用程序时,倒计时重新计算会为您提供正确的时间

你可以在stackblitz中看到


推荐阅读