Dart Future timeout()
Syntax & Examples

Future.timeout() method

The `timeout` method in Dart times out the future computation after the specified time limit.


Syntax of Future.timeout()

The syntax of Future.timeout() method is:

 Future<T> timeout(Duration timeLimit, { FutureOr<T> onTimeout() }) 

This timeout() method of Future time-out the future computation after timeLimit has passed.

Parameters

ParameterOptional/RequiredDescription
timeLimitrequiredA Duration object specifying the maximum duration to wait for the computation to complete.
onTimeoutoptionalA function to execute if the timeout occurs before the computation completes. This function should return a value of type `T` or a `FutureOr`.

Return Type

Future.timeout() returns value of type Future<T>.



✐ Examples

1 Timing out a delayed computation

In this example,

  1. We create a delayed future using Future.delayed with a delay of 2 seconds.
  2. We use the timeout method to set a timeout of 1 second.
  3. If the computation exceeds the time limit, the onTimeout function is executed, and we print a message and return -1.
  4. Otherwise, we print the result of the computation.

Dart Program

void main() {
  Future<int> future = Future.delayed(Duration(seconds: 2), () => 42);
  future.timeout(Duration(seconds: 1), onTimeout: () {
    print('Computation timed out!');
    return -1;
  }).then((value) {
    print('Result: $value');
  });
}

Output

Computation timed out!
Result: -1

2 Timing out a delayed computation with a success

In this example,

  1. We create a delayed future returning a string ('Hello, World!') with a delay of 3 seconds.
  2. We use the timeout method to set a timeout of 5 seconds.
  3. Since the computation completes within the time limit, no timeout occurs, and we print the result of the computation.

Dart Program

void main() {
  Future<String> future = Future.delayed(Duration(seconds: 3), () => 'Hello, World!');
  future.timeout(Duration(seconds: 5), onTimeout: () {
    print('Computation timed out!');
    return 'Timeout occurred';
  }).then((value) {
    print('Result: $value');
  });
}

Output

Result: Hello, World!

Summary

In this Dart tutorial, we learned about timeout() method of Future: the syntax and few working examples with output and detailed explanation for each example.