Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Delay as function #1

Open
theodesp opened this issue Jun 14, 2019 · 1 comment
Open

Delay as function #1

theodesp opened this issue Jun 14, 2019 · 1 comment

Comments

@theodesp
Copy link

theodesp commented Jun 14, 2019

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?

@moodysalem
Copy link

Would like this and also provide a function that produces exponential backoff delay functions

import Reattempt, {exponentialBackoff} from 'reattempt';

const result = await Reattempt.run({ times: 3, delay: exponentialBackoff({factor: 1.5, jitter: true}) }, doSomethingAsync);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants