1. 程式人生 > >定時獲取伺服器時間戳的一個類(Typescript)

定時獲取伺服器時間戳的一個類(Typescript)

export class TimeStampService {

  private _local_timestamp: number;   // 本地時間戳
  private _server_timestamp: 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._local_timestamp) {
      this._local_timestamp = new Date().getTime();
    } else {
      const now = new Date().getTime();


      // 提前30秒做一次非同步矯正
      if (now - this._local_timestamp > this.Duration - 1000 * 30) {
        this.getTimeDiffer();  // 更新差值 防止使用者修改本地時間
      }


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

    }
    this._server_timestamp = this._local_timestamp + this._timeDiffer;


    return this._server_timestamp;
  }

}