Path: blob/main/extensions/markdown-language-features/src/util/async.ts
3292 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 _cancelTimeout: Promise<T | null> | 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._cancelTimeout = null;21this._onSuccess = null;22this._task = null;23}2425dispose() {26this._doCancelTimeout();27}2829public trigger(task: ITask<T>, delay: number = this.defaultDelay): Promise<T | null> {30this._task = task;31if (delay >= 0) {32this._doCancelTimeout();33}3435if (!this._cancelTimeout) {36this._cancelTimeout = new Promise<T | undefined>((resolve) => {37this._onSuccess = resolve;38}).then(() => {39this._cancelTimeout = null;40this._onSuccess = null;41const result = this._task?.() ?? null;42this._task = null;43return result;44});45}4647if (delay >= 0 || this._timeout === null) {48this._timeout = setTimeout(() => {49this._timeout = null;50this._onSuccess?.(undefined);51}, delay >= 0 ? delay : this.defaultDelay);52}5354return this._cancelTimeout;55}5657private _doCancelTimeout(): void {58if (this._timeout !== null) {59clearTimeout(this._timeout);60this._timeout = null;61}62}63}646566