Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

检测网络 JS代码 #9

Open
super-zz opened this issue Aug 13, 2019 · 0 comments
Open

检测网络 JS代码 #9

super-zz opened this issue Aug 13, 2019 · 0 comments

Comments

@super-zz
Copy link
Owner

super-zz commented Aug 13, 2019

/**

interface INetworkDerection {
  maxTimes?: number
  intervalTime?: number
  requestUrl: string
}

export default class NetworkDerection {
  private maxTimes: number;
  private intervalTime: number;

  private timer: number | undefined;
  private requestUrl: string = '';
  private n: number = 0;
  private offline: boolean = false;
  private watcher: NetListeners;


  constructor(args: INetworkDerection) {

    this.requestUrl = args.requestUrl;
    this.intervalTime = args.intervalTime || 3 * 1000;
    this.maxTimes = args.maxTimes || 10;

    this.watcher = new NetListeners();
  }

  public start() {
    this.clearTimer();

    this.timer = window.setTimeout(() => {
      this.fetchStatus();

    }, this.intervalTime);

  }

  public stop() {
    this.clearTimer();
    this.n = 0;
  }

  private clearTimer() {
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = undefined;
    }
  }

  private fetchStatus() {
    const that = this;
    const request = new XMLHttpRequest();

    request.timeout = 10 * 1000;

    request.open('head', this.requestUrl);

    request.onreadystatechange = function() {
      // offline
      if (this.readyState === this.DONE) {
        if (this.status === 0) {
          if (++that.n > that.maxTimes) {
            that.n = 0;
            that.offline = true;
            that.watcher.emit('offline');
          }
        } else {
          if (that.offline === true) {
            that.offline = false;
            that.watcher.emit('online');
          }
        }

        that.start();
      }
    };

    request.send();
  }
}

// 监听事件
const eventNames = ['online', 'pending', 'offline'];
let listeners: any[] = [];
export class NetListeners {
  public on(eventName: string, callback: () => void) {
    if (!eventNames.includes(eventName)) {
      throw new Error('NetworkDetections: no defined func name' + eventName);
    }
    if (!(eventName in listeners)) {
      listeners[eventName] = [];
    }

    listeners[eventName].push(callback);

    return this;
  }

  public off(eventName: string, callback: () => void) {
    let currentEvent = listeners[eventName];
    let len = 0;
    if (currentEvent) {
      len = currentEvent.length;
      for (let i = len - 1; i >= 0; i--) {
        if (currentEvent[i] === callback) {
          currentEvent.splice(i, 1);
        }
      }
    }
    return this;
  }

  public emit(eventName: string, args?: any) {
    console.log('%c' + eventName, 'background: yellow');

    this.checkEvent(eventName);

    let callbacks = listeners[eventName];

    if (callbacks) {
      callbacks.forEach((callback: any) => callback.apply(null, args));
    }
  }

  private checkEvent (eventName: string) {
    if (!eventNames.includes(eventName)) {
      throw new Error('NetworkDetections: no defined func name' + eventName);
    }
  }

}
@super-zz super-zz changed the title 检测网络 检测网络 JS Aug 13, 2019
@super-zz super-zz changed the title 检测网络 JS 检测网络 JS代码 Aug 13, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant