0.0.13 • Published 4 months ago

add-timeout-to-function v0.0.13

Weekly downloads
-
License
MIT
Repository
-
Last release
4 months ago

This package is functional and has been tested but does not include documentation. It is primarily intended for personal use.

export function addTimeoutToFunction<T extends FnReturningPromise>({ fn, timeout, cleanupFn, shouldProvideTimeoutArgs = false }: { fn: T, timeout: number; cleanupFn?: () => void | Promise<void>; shouldProvideTimeoutArgs?: boolean; }) {
  return (...args: ExcludeLastFromTupleIfTimeoutArgs<Parameters<T>>) => addTimeoutToFunctionInternal<T>({ fn, args, timeout, cleanupFn, shouldProvideTimeoutArgs });
}


function addTimeoutToFunctionInternal<T extends FnReturningPromise>({ fn, args, timeout, cleanupFn, shouldProvideTimeoutArgs }: { fn: T, args: ExcludeLastFromTupleIfTimeoutArgs<Parameters<T>>, timeout: number, cleanupFn?: () => void | Promise<void>; shouldProvideTimeoutArgs: boolean; }): Promise<Awaited<ReturnType<T>>> {
  let onHasTimedOut: () => void | undefined;
  let timeoutArgsOrUndefined;
  if (shouldProvideTimeoutArgs) {
    const setHandleHasTimedOut = (fn: FnWithNoArgs) => onHasTimedOut = fn;
    timeoutArgsOrUndefined = { setHandleHasTimedOut };
  }
  let timeoutId: number | NodeJS.Timeout | undefined;
  return Promise.race<ReturnType<T>>(
    [
      fn(...args, timeoutArgsOrUndefined).then(result => {
        clearTimeout(timeoutId);
        return result;
      }),
      new Promise<void>(
        (_, reject) => {
          timeoutId = setTimeout(async () => {
            reject(new TimeoutError("Function timed out"));
            onHasTimedOut && onHasTimedOut();
            cleanupFn && cleanupFn();
          }, timeout);
        })
    ]);
}
0.0.13

4 months ago

0.0.12

5 months ago

0.0.11

5 months ago

0.0.10

5 months ago

0.0.9

5 months ago

0.0.8

5 months ago

0.0.7

5 months ago

0.0.6

5 months ago

0.0.5

5 months ago

0.0.4

5 months ago

0.0.3

5 months ago

0.0.2

5 months ago

0.0.1

5 months ago