Retry-Operation function

Date : 27th February 2026

Summary: A function that automatically retries if it fails.

While writing programs, we often need functionality that retries code when it fails for any reason.

For example, suppose we are developing a program that calls an API, and the API request fails due to a "Too Many Requests" error. In that case, we want it to retry so that the chances of receiving the expected response increase.

For that purpose, this function is created.

Use:

Arguments:

  1. operation: A function that you want to retry in case of failure.
  2. retries: Determines the maximum number of times you want to retry.
  3. delayMs: Time between two requests, in milliseconds.
  4. delayFromFirstAttempt: Determines whether to wait before the first request.

Return:

The return value of the first argument function.

Additional:

There are two additional features in this function.

  1. noRetry: Suppose you throw a custom exception, upon throwing of which, you don't want to retry. For example, if you try to get a response from any website, but received a 404 status code; in that case, you can specify that the request should not be retried.
  2. waitForInternet: Have you notice this code?

    Suppose you are calling an internet API from your local machine, and the internet connection is lost — what happens then? until the connection is restored, it waits.. Your code will not fail. This function is specifically developed with API calling in mind.

If you have any questions or suggestions, feel free to contact me.