0.0.13 • Published 2 years ago

add-timeout-to-function v0.0.13

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years 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

2 years ago

0.0.12

2 years ago

0.0.11

2 years ago

0.0.10

2 years ago

0.0.9

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago