首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >完全相同的倒计时器hh:mm:ss给每个人

完全相同的倒计时器hh:mm:ss给每个人
EN

Stack Overflow用户
提问于 2020-02-09 05:20:08
回答 1查看 96关注 0票数 1

我使用角拍卖网站,计算剩余时间从拍卖结束时间使用矩和显示计数器,但它失败时,用户改变他的时钟时间。

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-09 14:04:00

您可以尝试订阅文档焦点,然后获取服务器的dateTime表单。在找到客户端的日期与value.Some之间的不同之后,如

代码语言:javascript
复制
  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

代码语言:javascript
复制
<button (click)="click()">{{toogle?'stop':'start'}}</button>
{{time |date:'H:mm:ss':'UTC'}}

以及调用给我们日期时间的服务器的服务。

代码语言:javascript
复制
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中看到

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60133699

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档