Path: blob/main/extensions/merge-conflict/src/delayer.ts
3296 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45export interface ITask<T> {6(): T;7}89export class Delayer<T> {1011public defaultDelay: number;12private timeout: any; // Timer13private completionPromise: Promise<T> | null;14private onSuccess: ((value: T | PromiseLike<T> | undefined) => void) | null;15private task: ITask<T> | null;1617constructor(defaultDelay: number) {18this.defaultDelay = defaultDelay;19this.timeout = null;20this.completionPromise = null;21this.onSuccess = null;22this.task = null;23}2425public trigger(task: ITask<T>, delay: number = this.defaultDelay): Promise<T> {26this.task = task;27if (delay >= 0) {28this.cancelTimeout();29}3031if (!this.completionPromise) {32this.completionPromise = new Promise<T | undefined>((resolve) => {33this.onSuccess = resolve;34}).then(() => {35this.completionPromise = null;36this.onSuccess = null;37const result = this.task!();38this.task = null;39return result;40});41}4243if (delay >= 0 || this.timeout === null) {44this.timeout = setTimeout(() => {45this.timeout = null;46this.onSuccess!(undefined);47}, delay >= 0 ? delay : this.defaultDelay);48}4950return this.completionPromise;51}5253public forceDelivery(): Promise<T> | null {54if (!this.completionPromise) {55return null;56}57this.cancelTimeout();58const result = this.completionPromise;59this.onSuccess!(undefined);60return result;61}6263public isTriggered(): boolean {64return this.timeout !== null;65}6667public cancel(): void {68this.cancelTimeout();69this.completionPromise = null;70}7172private cancelTimeout(): void {73if (this.timeout !== null) {74clearTimeout(this.timeout);75this.timeout = null;76}77}78}798081