TimedQueue.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.TimedQueue = void 0;
  4. /**
  5. * Queue that is flushed automatically when it reaches some item limit
  6. * or when timeout is reached.
  7. */
  8. class TimedQueue {
  9. constructor() {
  10. /**
  11. * Queue will be flushed when it reaches this number of items.
  12. */
  13. this.itemLimit = 100;
  14. /**
  15. * Queue will be flushed after this many milliseconds.
  16. */
  17. this.timeLimit = 5000;
  18. /**
  19. * Method that will be called when queue is flushed.
  20. */
  21. this.onFlush = (list) => { };
  22. this.list = [];
  23. this.timer = null;
  24. }
  25. push(item) {
  26. this.list.push(item);
  27. if (this.list.length >= this.itemLimit) {
  28. this.flush();
  29. return;
  30. }
  31. if (!this.timer) {
  32. this.timer = setTimeout(() => {
  33. this.flush();
  34. }, this.timeLimit);
  35. }
  36. }
  37. flush() {
  38. const list = this.list;
  39. this.list = [];
  40. if (this.timer)
  41. clearTimeout(this.timer);
  42. this.timer = null;
  43. if (list.length) {
  44. try {
  45. this.onFlush(list);
  46. }
  47. catch (error) {
  48. // tslint:disable-next-line
  49. console.error('TimedQueue', error);
  50. }
  51. }
  52. return list;
  53. }
  54. }
  55. exports.TimedQueue = TimedQueue;