| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- import {
- map,
- remove
- } from 'lodash-es';
- class HeartBeatClass {
- static _instance = null;
- handlers = [];
- time = 1000;
- maxHandlerTimes = 1;
- _initTimes = 0;
- timer = 0;
- instance = null;
- constructor(time = 2000, maxHandlerTimes = 3000) {
- this.time = time;
- this.maxHandlerTimes = maxHandlerTimes;
- }
- static getInstance() {
- if (!HeartBeatClass._instance) {
- HeartBeatClass._instance = new HeartBeatClass(...arguments);
- }
- return HeartBeatClass._instance;
- }
- hasType(type) {
- if (!type) {
- return
- }
- return this.handlers.findIndex(item => item.type === type) > -1
- }
- handle({
- type,
- handler,
- data
- }) {
- clearInterval(this.timer);
- const hasType = this.handlers.findIndex(item => item.type === type) > -1;
- if (hasType) {
- remove(this.handlers, item => {
- return item.type === type;
- });
- }
- this.handlers.push({
- type,
- data,
- handler
- });
- if (!this.handlers.length) {
- return;
- }
- this.timer = setInterval(() => {
- if (this._initTimes < this.maxHandlerTimes) {
- this._initTimes++;
- Promise.all(
- map(this.handlers, handleItem => {
- return handleItem.handler(handleItem.data || {});
- })
- ).then(res => {
- remove(this.handlers, (item, index) => {
- return res[index];
- });
- if (!this.handlers.length) {
- clearInterval(this.timer);
- }
- });
- }
- }, this.time);
- }
-
- clearByType(type){
- const hasType = this.handlers.findIndex(item => item.type === type) > -1;
- if (hasType) {
- remove(this.handlers, item => {
- return item.type === type;
- });
- }
- }
- destory() {
- this._instance = null;
- this.handlers = [];
- clearInterval(this.timer);
- }
- }
- const HeartBeat = {
- getInstance: HeartBeatClass.getInstance
- };
- export default HeartBeat;
|