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