delay method

Duration delay(
  1. int attempt,
  2. int? retryAfter,
  3. DateTime? deadline
)

Delay after attempt number of attempts.

The next delay is computed as random value between range retry_interval * exponential_base^(attempts-1) and `retry_interval * exponential_base^(attempts) Example: for retry_interval=5, exponential_base=2, max_retry_delay=125, total=5 retry delays are random distributed values within the ranges of 5-10, 10-20, 20-40, 40-80, 80-125

Implementation

Duration delay(int attempt, int? retryAfter, DateTime? deadline) {
  assert(attempt >= 0, 'attempt cannot be negative');

  if (attempt <= 0) {
    return Duration.zero;
  } else if (attempt > maxRetries) {
    throw RetryException('Retry attempt beyond limit ($maxRetries)');
  }

  final rand = _rand.nextDouble();

  if (retryAfter != null && retryAfter > 0) {
    final addMilliseconds = (retryJitter.inMilliseconds * rand).toInt();
    return Duration(seconds: retryAfter, milliseconds: addMilliseconds);
  }

  var rangeStart =
      retryInterval.inMilliseconds * math.pow(exponentialBase, attempt - 1);
  var rangeStop =
      retryInterval.inMilliseconds * math.pow(exponentialBase, attempt);
  if (rangeStop > maxDelay.inMilliseconds) {
    rangeStop = maxDelay.inMilliseconds;
  }
  final num add = (rangeStop - rangeStart) * rand;
  var duration = Duration(milliseconds: (rangeStart + add).toInt());
  if (deadline != null) {
    final diff = deadline.difference(DateTime.now());
    if (duration > diff) {
      duration = diff;
      if (duration < Duration.zero) {
        duration = Duration.zero;
      }
    }
  }

  return duration;
}