Skip to content

Delay as function #1

@theodesp

Description

@theodesp

It would be nice if the delay parameter in ReattemptOptions was something like:

delay?: number | ((value: any, attempt: number) => number);

And in the reattemptAsync and reattempt we could check:

function tryDelayAsync(duration: number) {
        setTimeout(() => {
          currentAttempts--;
          reattemptAsync(fn(), fn, resolve, reject);
        }, duration);
 }

 if (isFunction(delay)) {
        const delayDuration = delay(error, currentAttempts - 1);
        if (delayDuration >= 0) {
          tryDelayAsync(delayDuration);
        } else {
          tryDelayAsync(defaultDelay); // defaultDelay = 0
        }
      } else {
        tryDelayAsync(delay);
      }

That way for example:

function delayFn(value: any, index: number): number {
      return 1000;
    }
    const promise = Reattempt.run({ times: 2, delay: delayFn }, fn);

The only thing that is somewhat ugly is the index parameters is decreasing over time instead of increasing. Ideally we want to pass an increasing sequence so for example we can calculate a exponental backoff like:

 function delayFn(value: any, index: number): number {
      let delay = Math.pow(2, index); // factor is 2
      const min = 0; // Min delay is 0
      const max = Math.floor(delay);
      delay = Math.floor(Math.random() * (max - min + 1)) + min;
      return Math.round(delay);
    }

I have a proof of concept on my local branch.

Thoughts?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions