| 330 | * } |
| 331 | */ |
| 332 | export class Delayer<T> implements IDisposable { |
| 333 | |
| 334 | private deferred: IScheduledLater | null; |
| 335 | private completionPromise: Promise<any> | null; |
| 336 | private doResolve: ((value?: any | Promise<any>) => void) | null; |
| 337 | private doReject: ((err: any) => void) | null; |
| 338 | private task: ITask<T | Promise<T>> | null; |
| 339 | |
| 340 | constructor(public defaultDelay: number | typeof MicrotaskDelay) { |
| 341 | this.deferred = null; |
| 342 | this.completionPromise = null; |
| 343 | this.doResolve = null; |
| 344 | this.doReject = null; |
| 345 | this.task = null; |
| 346 | } |
| 347 | |
| 348 | trigger(task: ITask<T | Promise<T>>, delay = this.defaultDelay): Promise<T> { |
| 349 | this.task = task; |
| 350 | this.cancelTimeout(); |
| 351 | |
| 352 | if (!this.completionPromise) { |
| 353 | this.completionPromise = new Promise((resolve, reject) => { |
| 354 | this.doResolve = resolve; |
| 355 | this.doReject = reject; |
| 356 | }).then(() => { |
| 357 | this.completionPromise = null; |
| 358 | this.doResolve = null; |
| 359 | if (this.task) { |
| 360 | const task = this.task; |
| 361 | this.task = null; |
| 362 | return task(); |
| 363 | } |
| 364 | return undefined; |
| 365 | }); |
| 366 | } |
| 367 | |
| 368 | const fn = () => { |
| 369 | this.deferred = null; |
| 370 | this.doResolve?.(null); |
| 371 | }; |
| 372 | |
| 373 | this.deferred = delay === MicrotaskDelay ? microtaskDeferred(fn) : timeoutDeferred(delay, fn); |
| 374 | |
| 375 | return this.completionPromise; |
| 376 | } |
| 377 | |
| 378 | isTriggered(): boolean { |
| 379 | return !!this.deferred?.isTriggered(); |
| 380 | } |
| 381 | |
| 382 | cancel(): void { |
| 383 | this.cancelTimeout(); |
| 384 | |
| 385 | if (this.completionPromise) { |
| 386 | this.doReject?.(new CancellationError()); |
| 387 | this.completionPromise = null; |
| 388 | } |
| 389 | } |
nothing calls this directly
no outgoing calls
no test coverage detected