# All files / src/utils delay.ts

94.44% Statements 17/18
60% Branches 3/5
100% Functions 3/3
94.44% Lines 17/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    391x

    1x

    228x
    228x
    228x

    228x
    1x
    1x

    1x

    1x
    1x

    1x
    1x
    1x
    1x
    1x

    1x

     import Promise from 'bluebird';

    /**
    * Creates a function that delays invoking `func` until after `wait` milliseconds have elapsed
    * and the running `func` has resolved/rejected.
    * @param func the promise-returning function to delay,
    *        func should take in a single array
    * @param wait the number of milliseconds to delay
    * @returns delayedFunc that takes in a single argument (either an array or a single value)
    */
    export function delay<T>(func: (arg: T[]) => Promise<unknown>, wait: number) {
      let context: any;
      let pendingArgs: T[] = [];
      let runningPromise: Promise<unknown> = Promise.resolve();
      let waitingPromise: Promise<unknown> | null = null;

      return function (this: any, arg: T | T[]) {
        context = this;
        Iif (Array.isArray(arg)) {
          pendingArgs = pendingArgs.concat(arg);
        } else {
          pendingArgs.push(arg);
        }

        if (waitingPromise === null) {
          waitingPromise = Promise.all([Promise.delay(wait), runningPromise])
            .then(() => {
              runningPromise = waitingPromise || Promise.resolve();
              waitingPromise = null;
              const funcPromise = func.apply(context, [pendingArgs]);
              pendingArgs = [];
              return funcPromise;
            });
        }

        return waitingPromise;
      };
    }