ee85d1ed924b8e01a059dad29673c1391f52e603168f3546d2daafed2062733b5ff4c4f631552ad2e631da5b85a34fe13282c3310ece5944f4110359cf1416 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { Immediate } from '../util/Immediate';
  2. import { AsyncAction } from './AsyncAction';
  3. import { AsapScheduler } from './AsapScheduler';
  4. import { SchedulerAction } from '../types';
  5. /**
  6. * We need this JSDoc comment for affecting ESDoc.
  7. * @ignore
  8. * @extends {Ignored}
  9. */
  10. export class AsapAction<T> extends AsyncAction<T> {
  11. constructor(protected scheduler: AsapScheduler,
  12. protected work: (this: SchedulerAction<T>, state?: T) => void) {
  13. super(scheduler, work);
  14. }
  15. protected requestAsyncId(scheduler: AsapScheduler, id?: any, delay: number = 0): any {
  16. // If delay is greater than 0, request as an async action.
  17. if (delay !== null && delay > 0) {
  18. return super.requestAsyncId(scheduler, id, delay);
  19. }
  20. // Push the action to the end of the scheduler queue.
  21. scheduler.actions.push(this);
  22. // If a microtask has already been scheduled, don't schedule another
  23. // one. If a microtask hasn't been scheduled yet, schedule one now. Return
  24. // the current scheduled microtask id.
  25. return scheduler.scheduled || (scheduler.scheduled = Immediate.setImmediate(
  26. scheduler.flush.bind(scheduler, null)
  27. ));
  28. }
  29. protected recycleAsyncId(scheduler: AsapScheduler, id?: any, delay: number = 0): any {
  30. // If delay exists and is greater than 0, or if the delay is null (the
  31. // action wasn't rescheduled) but was originally scheduled as an async
  32. // action, then recycle as an async action.
  33. if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
  34. return super.recycleAsyncId(scheduler, id, delay);
  35. }
  36. // If the scheduler queue is empty, cancel the requested microtask and
  37. // set the scheduled flag to undefined so the next AsapAction will schedule
  38. // its own.
  39. if (scheduler.actions.length === 0) {
  40. Immediate.clearImmediate(id);
  41. scheduler.scheduled = undefined;
  42. }
  43. // Return undefined so the action knows to request a new async id if it's rescheduled.
  44. return undefined;
  45. }
  46. }