3a7fdc13dc60ac4053405ef5d97ea944931e8b8a20927c87f227c8adaf849d22d6a89160ed64f8a2a3d209153c0da8d1a813e4f9825bcfcfc9f6d0822a7a07 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { Scheduler } from '../Scheduler';
  2. import { Action } from './Action';
  3. import { AsyncAction } from './AsyncAction';
  4. import { TimerHandle } from './timerHandle';
  5. export class AsyncScheduler extends Scheduler {
  6. public actions: Array<AsyncAction<any>> = [];
  7. /**
  8. * A flag to indicate whether the Scheduler is currently executing a batch of
  9. * queued actions.
  10. * @internal
  11. */
  12. public _active: boolean = false;
  13. /**
  14. * An internal ID used to track the latest asynchronous task such as those
  15. * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and
  16. * others.
  17. * @internal
  18. */
  19. public _scheduled: TimerHandle | undefined;
  20. constructor(SchedulerAction: typeof Action, now: () => number = Scheduler.now) {
  21. super(SchedulerAction, now);
  22. }
  23. public flush(action: AsyncAction<any>): void {
  24. const { actions } = this;
  25. if (this._active) {
  26. actions.push(action);
  27. return;
  28. }
  29. let error: any;
  30. this._active = true;
  31. do {
  32. if ((error = action.execute(action.state, action.delay))) {
  33. break;
  34. }
  35. } while ((action = actions.shift()!)); // exhaust the scheduler queue
  36. this._active = false;
  37. if (error) {
  38. while ((action = actions.shift()!)) {
  39. action.unsubscribe();
  40. }
  41. throw error;
  42. }
  43. }
  44. }