|
import { AsyncAction } from './AsyncAction'; |
|
import { Subscription } from '../Subscription'; |
|
import { AsyncScheduler } from './AsyncScheduler'; |
|
import { SchedulerAction } from '../types'; |
|
import { TimerHandle } from './timerHandle'; |
|
|
|
export class VirtualTimeScheduler extends AsyncScheduler { |
|
|
|
static frameTimeFactor = 10; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public frame: number = 0; |
|
|
|
|
|
|
|
|
|
|
|
public index: number = -1; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
constructor(schedulerActionCtor: typeof AsyncAction = VirtualAction as any, public maxFrames: number = Infinity) { |
|
super(schedulerActionCtor, () => this.frame); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
public flush(): void { |
|
const { actions, maxFrames } = this; |
|
let error: any; |
|
let action: AsyncAction<any> | undefined; |
|
|
|
while ((action = actions[0]) && action.delay <= maxFrames) { |
|
actions.shift(); |
|
this.frame = action.delay; |
|
|
|
if ((error = action.execute(action.state, action.delay))) { |
|
break; |
|
} |
|
} |
|
|
|
if (error) { |
|
while ((action = actions.shift())) { |
|
action.unsubscribe(); |
|
} |
|
throw error; |
|
} |
|
} |
|
} |
|
|
|
export class VirtualAction<T> extends AsyncAction<T> { |
|
protected active: boolean = true; |
|
|
|
constructor( |
|
protected scheduler: VirtualTimeScheduler, |
|
protected work: (this: SchedulerAction<T>, state?: T) => void, |
|
protected index: number = (scheduler.index += 1) |
|
) { |
|
super(scheduler, work); |
|
this.index = scheduler.index = index; |
|
} |
|
|
|
public schedule(state?: T, delay: number = 0): Subscription { |
|
if (Number.isFinite(delay)) { |
|
if (!this.id) { |
|
return super.schedule(state, delay); |
|
} |
|
this.active = false; |
|
|
|
|
|
|
|
|
|
const action = new VirtualAction(this.scheduler, this.work); |
|
this.add(action); |
|
return action.schedule(state, delay); |
|
} else { |
|
|
|
|
|
return Subscription.EMPTY; |
|
} |
|
} |
|
|
|
protected requestAsyncId(scheduler: VirtualTimeScheduler, id?: any, delay: number = 0): TimerHandle { |
|
this.delay = scheduler.frame + delay; |
|
const { actions } = scheduler; |
|
actions.push(this); |
|
(actions as Array<VirtualAction<T>>).sort(VirtualAction.sortActions); |
|
return 1; |
|
} |
|
|
|
protected recycleAsyncId(scheduler: VirtualTimeScheduler, id?: any, delay: number = 0): TimerHandle | undefined { |
|
return undefined; |
|
} |
|
|
|
protected _execute(state: T, delay: number): any { |
|
if (this.active === true) { |
|
return super._execute(state, delay); |
|
} |
|
} |
|
|
|
private static sortActions<T>(a: VirtualAction<T>, b: VirtualAction<T>) { |
|
if (a.delay === b.delay) { |
|
if (a.index === b.index) { |
|
return 0; |
|
} else if (a.index > b.index) { |
|
return 1; |
|
} else { |
|
return -1; |
|
} |
|
} else if (a.delay > b.delay) { |
|
return 1; |
|
} else { |
|
return -1; |
|
} |
|
} |
|
} |
|
|