import 'dart:io'; sleep(Duration(seconds:1));
To prevent multiple awaits, chaining futures in . then(), you can simply use Future. wait([]) that returns an array of results you were waiting for. If any of those Futures within that array fails, Future.
2019 edition:
await Future.delayed(Duration(seconds: 1));
import 'dart:io';
sleep(Duration(seconds:1));
Note: This blocks the entire process (isolate), so other async functions will not be processed. It's also not available on the web because Javascript is really async-only.
You can also use the Future.delayed factory to complete a future after a delay. Here is an example of two functions that return a string asynchronously after a delay:
import 'dart:async';
Future sleep1() {
return new Future.delayed(const Duration(seconds: 1), () => "1");
}
Future sleep2() {
return new Future.delayed(const Duration(seconds: 2), () => "2");
}
It's not always what you want (sometimes you want Future.delayed
), but if you really want to sleep in your Dart command-line app, you can use dart:io's sleep()
:
import 'dart:io';
main() {
sleep(const Duration(seconds:1));
}
I found that there are several implementations in Dart to make the code delay execution:
new Future.delayed(const Duration(seconds: 1)); //recommend
new Timer(const Duration(seconds: 1), ()=>print("1 second later."));
sleep(const Duration(seconds: 1)); //import 'dart:io';
new Stream.periodic(const Duration(seconds: 1), (_) => print("1 second later.")).first.then((_)=>print("Also 1 second later."));
//new Stream.periodic(const Duration(seconds: 1)).first.then((_)=>print("Also 1 second later."));
For Dart 2+ syntax , in a async function context:
import 'package:meta/meta.dart'; //for @required annotation
void main() async {
void justWait({@required int numberOfSeconds}) async {
await Future.delayed(Duration(seconds: numberOfSeconds));
}
await justWait(numberOfSeconds: 5);
}
This a useful mock that can take an optional parameter to mock an error:
Future _mockService([dynamic error]) {
return new Future.delayed(const Duration(seconds: 2), () {
if (error != null) {
throw error;
}
});
}
You can use it like this:
await _mockService(new Exception('network error'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With