async-stream.js 957 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * @file async-stream.js
  3. */
  4. import Stream from '@videojs/vhs-utils/es/stream.js';
  5. /**
  6. * A wrapper around the Stream class to use setTimeout
  7. * and run stream "jobs" Asynchronously
  8. *
  9. * @class AsyncStream
  10. * @extends Stream
  11. */
  12. export default class AsyncStream extends Stream {
  13. constructor() {
  14. super(Stream);
  15. this.jobs = [];
  16. this.delay = 1;
  17. this.timeout_ = null;
  18. }
  19. /**
  20. * process an async job
  21. *
  22. * @private
  23. */
  24. processJob_() {
  25. this.jobs.shift()();
  26. if (this.jobs.length) {
  27. this.timeout_ = setTimeout(
  28. this.processJob_.bind(this),
  29. this.delay
  30. );
  31. } else {
  32. this.timeout_ = null;
  33. }
  34. }
  35. /**
  36. * push a job into the stream
  37. *
  38. * @param {Function} job the job to push into the stream
  39. */
  40. push(job) {
  41. this.jobs.push(job);
  42. if (!this.timeout_) {
  43. this.timeout_ = setTimeout(
  44. this.processJob_.bind(this),
  45. this.delay
  46. );
  47. }
  48. }
  49. }