Skip to content

Instantly share code, notes, and snippets.

@lxsmnsyc
Last active October 13, 2020 08:40
Show Gist options
  • Save lxsmnsyc/7935c5db4d935f71a2107bf0edccb85e to your computer and use it in GitHub Desktop.
Save lxsmnsyc/7935c5db4d935f71a2107bf0edccb85e to your computer and use it in GitHub Desktop.

Revisions

  1. lxsmnsyc revised this gist Oct 13, 2020. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions debounce-async.ts
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,7 @@
    export type AsyncCallback<T extends any[]> = (...args: T) => Promise<void>;
    export type DebouncedAsync<T extends any[]> = (...args: T) => void;

    export function debounceAsync<T extends any[]>(callback: AsyncCallback<T>): DebouncedAsync<T> {
    export function debounceAsync<T extends any[]>(callback: AsyncCallback<T>, duration: number): DebouncedAsync<T> {
    let lifecycle: PromiseLifecycle;
    let timeout: number;

    @@ -16,7 +16,7 @@ export function debounceAsync<T extends any[]>(callback: AsyncCallback<T>): Debo
    };

    timeout = window.setTimeout(() => {
    promiseLifecycle(lifecycle, func.call(null, ...args));
    promiseLifecycle(lifecycle, callback.call(null, ...args));
    }, duration);
    }

  2. lxsmnsyc created this gist Oct 13, 2020.
    24 changes: 24 additions & 0 deletions debounce-async.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    export type AsyncCallback<T extends any[]> = (...args: T) => Promise<void>;
    export type DebouncedAsync<T extends any[]> = (...args: T) => void;

    export function debounceAsync<T extends any[]>(callback: AsyncCallback<T>): DebouncedAsync<T> {
    let lifecycle: PromiseLifecycle;
    let timeout: number;

    function control(...args: T) {
    if (timeout) {
    lifecycle.alive = false;
    window.clearTimeout(timeout);
    }

    lifecycle = {
    alive: true,
    };

    timeout = window.setTimeout(() => {
    promiseLifecycle(lifecycle, func.call(null, ...args));
    }, duration);
    }

    return control;
    }
    23 changes: 23 additions & 0 deletions promise-lifecycle.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    export interface PromiseLifecycle {
    alive: boolean;
    }

    export function promiseLifecycle<T>(
    lifecycle: PromiseLifecycle,
    promise: Promise<T>,
    ): Promise<T> {
    return new Promise<T>((resolve, reject) => {
    promise.then(
    (value) => {
    if (lifecycle.alive) {
    resolve(value);
    }
    },
    (value) => {
    if (lifecycle.alive) {
    reject(value);
    }
    },
    );
    });
    }