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