HeartBeat.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import {
  2. map,
  3. remove
  4. } from 'lodash-es';
  5. class HeartBeatClass {
  6. static _instance = null;
  7. handlers = [];
  8. time = 1000;
  9. maxHandlerTimes = 1;
  10. _initTimes = 0;
  11. timer = 0;
  12. instance = null;
  13. constructor(time = 2000, maxHandlerTimes = 3000) {
  14. this.time = time;
  15. this.maxHandlerTimes = maxHandlerTimes;
  16. }
  17. static getInstance() {
  18. if (!HeartBeatClass._instance) {
  19. HeartBeatClass._instance = new HeartBeatClass(...arguments);
  20. }
  21. return HeartBeatClass._instance;
  22. }
  23. hasType(type) {
  24. if (!type) {
  25. return
  26. }
  27. return this.handlers.findIndex(item => item.type === type) > -1
  28. }
  29. handle({
  30. type,
  31. handler,
  32. data
  33. }) {
  34. clearInterval(this.timer);
  35. const hasType = this.handlers.findIndex(item => item.type === type) > -1;
  36. if (hasType) {
  37. remove(this.handlers, item => {
  38. return item.type === type;
  39. });
  40. }
  41. this.handlers.push({
  42. type,
  43. data,
  44. handler
  45. });
  46. if (!this.handlers.length) {
  47. return;
  48. }
  49. this.timer = setInterval(() => {
  50. if (this._initTimes < this.maxHandlerTimes) {
  51. this._initTimes++;
  52. Promise.all(
  53. map(this.handlers, handleItem => {
  54. return handleItem.handler(handleItem.data || {});
  55. })
  56. ).then(res => {
  57. remove(this.handlers, (item, index) => {
  58. return res[index];
  59. });
  60. if (!this.handlers.length) {
  61. clearInterval(this.timer);
  62. }
  63. });
  64. }
  65. }, this.time);
  66. }
  67. clearByType(type){
  68. const hasType = this.handlers.findIndex(item => item.type === type) > -1;
  69. if (hasType) {
  70. remove(this.handlers, item => {
  71. return item.type === type;
  72. });
  73. }
  74. }
  75. destory() {
  76. this._instance = null;
  77. this.handlers = [];
  78. clearInterval(this.timer);
  79. }
  80. }
  81. const HeartBeat = {
  82. getInstance: HeartBeatClass.getInstance
  83. };
  84. export default HeartBeat;