HeartBeat.js 1.9 KB

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