timeUntilAvailable method

Duration timeUntilAvailable([
  1. int tokens = 1
])

How long until tokens (default 1) would be available, or Duration.zero if they are available now. Pairs with tryAcquire so a caller can schedule a retry instead of busy-polling. Throws ArgumentError on an impossible request (see tryAcquire). Audited: 2026-06-12 11:26 EDT

Implementation

Duration timeUntilAvailable([int tokens = 1]) {
  _validate(tokens);
  _refill();
  if (_tokens >= tokens) {
    return Duration.zero;
  }
  // Convert the token deficit to wait time at the refill rate, rounding up so
  // the returned instant is the first moment the request can actually succeed.
  final double deficit = tokens - _tokens;
  final int micros = (deficit / tokensPerSecond * Duration.microsecondsPerSecond).ceil();
  return Duration(microseconds: micros);
}