Skip to content

retry ​

The retry function executes a provided function and retries on error, up to a maximum number of attempts.

Syntax ​

typescript
retry(callback, attempts)

Parameters ​

NameTypeDescription
callbackFunctionFunction to be executed, which may throw an error.
attemptsnumberMaximum number of attempts (positive integer).

Return Value ​

TypeDescription
anyValue returned by the callback if it succeeds, or throws if all fail.

Examples ​

typescript
let count = 0;
const result = retry(() => {
  count++;
  if (count < 3) throw new Error('Failure!');
  return 'Success';
}, 5);
// result: 'Success' (after 3 attempts)

retry(() => { throw new Error('Always fails'); }, 2);
// Throws error after 2 attempts

Notes ​

  • Throws a TypeError if the callback is not a function or if attempts is not a positive integer.
  • Useful for operations that may temporarily fail, such as network requests.

References ​

Released under the MIT License.