timer.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import { Observable, Observer } from '../Misc/observable';
  2. import { Nullable } from '../types';
  3. import { IDisposable } from '../scene';
  4. /**
  5. * Construction options for a timer
  6. */
  7. export interface ITimerOptions<T> {
  8. /**
  9. * Time-to-end
  10. */
  11. timeout: number;
  12. /**
  13. * The context observable is used to calculate time deltas and provides the context of the timer's callbacks. Will usually be OnBeforeRenderObservable.
  14. * Countdown calculation is done ONLY when the observable is notifying its observers, meaning that if
  15. * you choose an observable that doesn't trigger too often, the wait time might extend further than the requested max time
  16. */
  17. contextObservable: Observable<T>;
  18. /**
  19. * Optional parameters when adding an observer to the observable
  20. */
  21. observableParameters?: {
  22. mask?: number;
  23. insertFirst?: boolean;
  24. scope?: any;
  25. };
  26. /**
  27. * An optional break condition that will stop the times prematurely. In this case onEnded will not be triggered!
  28. */
  29. breakCondition?: (data?: ITimerData<T>) => boolean;
  30. /**
  31. * Will be triggered when the time condition has met
  32. */
  33. onEnded?: (data: ITimerData<any>) => void;
  34. /**
  35. * Will be triggered when the break condition has met (prematurely ended)
  36. */
  37. onAborted?: (data: ITimerData<any>) => void;
  38. /**
  39. * Optional function to execute on each tick (or count)
  40. */
  41. onTick?: (data: ITimerData<any>) => void;
  42. }
  43. /**
  44. * An interface defining the data sent by the timer
  45. */
  46. export interface ITimerData<T> {
  47. /**
  48. * When did it start
  49. */
  50. startTime: number;
  51. /**
  52. * Time now
  53. */
  54. currentTime: number;
  55. /**
  56. * Time passed since started
  57. */
  58. deltaTime: number;
  59. /**
  60. * How much is completed, in [0.0...1.0].
  61. * Note that this CAN be higher than 1 due to the fact that we don't actually measure time but delta between observable calls
  62. */
  63. completeRate: number;
  64. /**
  65. * What the registered observable sent in the last count
  66. */
  67. payload: T;
  68. }
  69. /**
  70. * The current state of the timer
  71. */
  72. export enum TimerState {
  73. /**
  74. * Timer initialized, not yet started
  75. */
  76. INIT,
  77. /**
  78. * Timer started and counting
  79. */
  80. STARTED,
  81. /**
  82. * Timer ended (whether aborted or time reached)
  83. */
  84. ENDED
  85. }
  86. /**
  87. * A simple version of the timer. Will take options and start the timer immediately after calling it
  88. *
  89. * @param options options with which to initialize this timer
  90. */
  91. export function setAndStartTimer(options: ITimerOptions<any>): Nullable<Observer<any>> {
  92. let timer = 0;
  93. const startTime = Date.now();
  94. options.observableParameters = options.observableParameters ?? {};
  95. const observer = options.contextObservable.add((payload: any) => {
  96. const now = Date.now();
  97. timer = now - startTime;
  98. const data: ITimerData<any> = {
  99. startTime,
  100. currentTime: now,
  101. deltaTime: timer,
  102. completeRate: timer / options.timeout,
  103. payload
  104. };
  105. options.onTick && options.onTick(data);
  106. if (options.breakCondition && options.breakCondition()) {
  107. options.contextObservable.remove(observer);
  108. options.onAborted && options.onAborted(data);
  109. }
  110. if (timer >= options.timeout) {
  111. options.contextObservable.remove(observer);
  112. options.onEnded && options.onEnded(data);
  113. }
  114. }, options.observableParameters.mask, options.observableParameters.insertFirst, options.observableParameters.scope);
  115. return observer;
  116. }
  117. /**
  118. * An advanced implementation of a timer class
  119. */
  120. export class AdvancedTimer<T = any> implements IDisposable {
  121. /**
  122. * Will notify each time the timer calculates the remaining time
  123. */
  124. public onEachCountObservable: Observable<ITimerData<T>> = new Observable();
  125. /**
  126. * Will trigger when the timer was aborted due to the break condition
  127. */
  128. public onTimerAbortedObservable: Observable<ITimerData<T>> = new Observable();
  129. /**
  130. * Will trigger when the timer ended successfully
  131. */
  132. public onTimerEndedObservable: Observable<ITimerData<T>> = new Observable();
  133. /**
  134. * Will trigger when the timer state has changed
  135. */
  136. public onStateChangedObservable: Observable<TimerState> = new Observable();
  137. private _observer: Nullable<Observer<T>> = null;
  138. private _contextObservable: Observable<T>;
  139. private _observableParameters: {
  140. mask?: number;
  141. insertFirst?: boolean;
  142. scope?: any;
  143. };
  144. private _startTime: number;
  145. private _timer: number;
  146. private _state: TimerState;
  147. private _breakCondition: (data: ITimerData<T>) => boolean;
  148. private _timeToEnd: number;
  149. private _breakOnNextTick: boolean = false;
  150. /**
  151. * Will construct a new advanced timer based on the options provided. Timer will not start until start() is called.
  152. * @param options construction options for this advanced timer
  153. */
  154. constructor(options: ITimerOptions<T>) {
  155. this._setState(TimerState.INIT);
  156. this._contextObservable = options.contextObservable;
  157. this._observableParameters = options.observableParameters ?? {};
  158. this._breakCondition = options.breakCondition ?? (() => false);
  159. if (options.onEnded) {
  160. this.onTimerEndedObservable.add(options.onEnded);
  161. }
  162. if (options.onTick) {
  163. this.onEachCountObservable.add(options.onTick);
  164. }
  165. if (options.onAborted) {
  166. this.onTimerAbortedObservable.add(options.onAborted);
  167. }
  168. }
  169. /**
  170. * set a breaking condition for this timer. Default is to never break during count
  171. * @param predicate the new break condition. Returns true to break, false otherwise
  172. */
  173. public set breakCondition(predicate: (data: ITimerData<T>) => boolean) {
  174. this._breakCondition = predicate;
  175. }
  176. /**
  177. * Reset ALL associated observables in this advanced timer
  178. */
  179. public clearObservables() {
  180. this.onEachCountObservable.clear();
  181. this.onTimerAbortedObservable.clear();
  182. this.onTimerEndedObservable.clear();
  183. this.onStateChangedObservable.clear();
  184. }
  185. /**
  186. * Will start a new iteration of this timer. Only one instance of this timer can run at a time.
  187. *
  188. * @param timeToEnd how much time to measure until timer ended
  189. */
  190. public start(timeToEnd: number = this._timeToEnd) {
  191. if (this._state === TimerState.STARTED) {
  192. throw new Error('Timer already started. Please stop it before starting again');
  193. }
  194. this._timeToEnd = timeToEnd;
  195. this._startTime = Date.now();
  196. this._timer = 0;
  197. this._observer = this._contextObservable.add(this._tick, this._observableParameters.mask, this._observableParameters.insertFirst, this._observableParameters.scope);
  198. this._setState(TimerState.STARTED);
  199. }
  200. /**
  201. * Will force a stop on the next tick.
  202. */
  203. public stop() {
  204. if (this._state !== TimerState.STARTED) {
  205. return;
  206. }
  207. this._breakOnNextTick = true;
  208. }
  209. /**
  210. * Dispose this timer, clearing all resources
  211. */
  212. public dispose() {
  213. if (this._observer) {
  214. this._contextObservable.remove(this._observer);
  215. }
  216. this.clearObservables();
  217. }
  218. private _setState(newState: TimerState) {
  219. this._state = newState;
  220. this.onStateChangedObservable.notifyObservers(this._state);
  221. }
  222. private _tick = (payload: T) => {
  223. const now = Date.now();
  224. this._timer = now - this._startTime;
  225. const data: ITimerData<T> = {
  226. startTime: this._startTime,
  227. currentTime: now,
  228. deltaTime: this._timer,
  229. completeRate: this._timer / this._timeToEnd,
  230. payload
  231. };
  232. const shouldBreak = this._breakOnNextTick || this._breakCondition(data);
  233. if (shouldBreak || this._timer >= this._timeToEnd) {
  234. this._stop(data, shouldBreak);
  235. } else {
  236. this.onEachCountObservable.notifyObservers(data);
  237. }
  238. }
  239. private _stop(data: ITimerData<T>, aborted: boolean = false) {
  240. this._contextObservable.remove(this._observer);
  241. this._setState(TimerState.ENDED);
  242. if (aborted) {
  243. this.onTimerAbortedObservable.notifyObservers(data);
  244. } else {
  245. this.onTimerEndedObservable.notifyObservers(data);
  246. }
  247. }
  248. }