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

2019-05-28 16:44:10 浏览数 (1)

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

0 人点赞