Path: blob/main/extensions/copilot/src/util/common/debounce.ts
13397 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*--------------------------------------------------------------------------------------------*/45type DebounceState = {6timer: any;7reject: (reason?: any) => void;8};910/**11* Debouncer class for async code.12*13* Implements "trailing" debouncing as described here:14* https://css-tricks.com/debouncing-throttling-explained-examples/#aa-debounce15*16* For a given instance of this class, at most one call to `debounce` can be17* in progress at a time. A subsequent call will trigger rejection of the promise returned18* by the previous call.19*/20export class Debouncer {21private state: DebounceState | undefined;2223/**24* Wait for the specified number of milliseconds, then resolve.25* Rejects if another call is made to `debounce` on this object in the meantime.26*/27public async debounce(ms: number): Promise<void> {28if (this.state) {29clearTimeout(this.state.timer);30this.state.reject();31this.state = undefined;32}33return new Promise<void>((resolve, reject) => {34this.state = {35timer: setTimeout(() => resolve(), ms),36reject,37};38});39}40}4142/** Debounce function for sync functions */43export function debounce<T extends (...args: any[]) => any>(44ms: number,45callback: T46): (...args: Parameters<T>) => Promise<ReturnType<T>> {47let timer: any | undefined;4849return (...args: Parameters<T>) => {50if (timer) {51clearTimeout(timer);52}53return new Promise<ReturnType<T>>(resolve => {54timer = setTimeout(() => {55const returnValue = callback(...args) as ReturnType<T>;56resolve(returnValue);57}, ms);58});59};60}616263