You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TaskQueue.js 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. const logger = require('jitsi-meet-logger').getLogger(__filename);
  2. /**
  3. * Manages a queue of functions where the current function in progress will
  4. * automatically execute the next queued function.
  5. */
  6. export class TaskQueue {
  7. /**
  8. * Creates a new instance of {@link TaskQueue} and sets initial instance
  9. * variable values.
  10. */
  11. constructor() {
  12. this._queue = [];
  13. this._currentTask = null;
  14. this._onTaskComplete = this._onTaskComplete.bind(this);
  15. }
  16. /**
  17. * Adds a new function to the queue. It will be immediately invoked if no
  18. * other functions are queued.
  19. *
  20. * @param {Function} taskFunction - The function to be queued for execution.
  21. * @private
  22. * @returns {void}
  23. */
  24. enqueue(taskFunction) {
  25. this._queue.push(taskFunction);
  26. this._executeNext();
  27. }
  28. /**
  29. * If no queued task is currently executing, invokes the first task in the
  30. * queue if any.
  31. *
  32. * @private
  33. * @returns {void}
  34. */
  35. _executeNext() {
  36. if (this._currentTask) {
  37. logger.warn('Task queued while a task is in progress.');
  38. return;
  39. }
  40. this._currentTask = this._queue.shift() || null;
  41. if (this._currentTask) {
  42. this._currentTask(this._onTaskComplete);
  43. }
  44. }
  45. /**
  46. * Prepares to invoke the next function in the queue.
  47. *
  48. * @private
  49. * @returns {void}
  50. */
  51. _onTaskComplete() {
  52. this._currentTask = null;
  53. this._executeNext();
  54. }
  55. }