首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >定时获取服务器时间戳的一个类(Typescript)

定时获取服务器时间戳的一个类(Typescript)

作者头像
lilugirl
发布2019-05-28 16:44:10
1.4K0
发布2019-05-28 16:44:10
举报
文章被收录于专栏:前端导学前端导学
export class TimeStampService {

  private _localTimestamp: number;   // 本地时间戳
  private _serveTimestamp: number;  // 服务器端时间戳
  private _duration: number = 1000 * 60 * 5; // 时间戳更新频率 (毫秒)
  private _timeDiffer: number; // 服务器和本地的时间差 服务器-本地

  constructor(

  ) {
    this._timeDiffer = 0;
    this.getTimeDiffer();

  }

  private getTimeDiffer() {

    const xhr = new XMLHttpRequest();
    xhr.open('get', environment.URL_TIME, true);
    const that = this;

    xhr.onload = function () {
      if (this.status === 200) {

        const result = JSON.parse(this.response);
        const now = new Date().getTime();
        that._timeDiffer = result.data.timestamp - now;

      }
    };
    xhr.onerror = function () {
      console.log('xhr error', xhr);

    };
    xhr.send();



  }

  get Duration() {
    return this._duration;
  }

  get ServerTimeStamp() {
    if (!this._localTimestamp) {
      this._localTimestamp = new Date().getTime();
    } else {
      const now = new Date().getTime();


      // 提前30秒做一次异步矫正
      if (now - this._localTimestamp > this.Duration - 1000 * 30) {
        this.getTimeDiffer();  // 更新差值 防止用户修改本地时间
      }


      if (now - this._localTimestamp > this.Duration) {
        this._localTimestamp = now;
      }

    }
    this._serveTimestamp = this._localTimestamp + this._timeDiffer;


    return this._serveTimestamp;
  }


}

我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3cjlyulghccgo

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档