Below is a simple dart code that returns a future and completes with error after 220 milliseconds. I tried to catch the error with a timer object at the duration of 219 milliseconds.
var future = Future<int>.delayed(
const Duration(milliseconds: 220), () => throw Exception("Hello!"));
Timer(const Duration(milliseconds: 219),
() => future.then(print, onError: (err) => print(err)));
I have noticed sometimes the callback to the timer object catches the error, but other times I see failures.
Why?
My understanding: I think it's because of short difference in the duration (220 - 219 = 1 milliseconds). If I increase the difference (says timer is set at 100 milliseconds), the callback always catches the error as expected. Does it imply the time computations are not so accurate in the dart language (or maybe in all programming languages). More detailed explanation on this behavior will be welcomed.
I'm new to dart and new to concepts like Future
. So, please be lenient on me.
"Does it imply the time computations are not so accurate in the dart language" No, it implies that it took more than 1ms between when you scheduled the Future and when you registered the error handler. That could happen for a number of reasons (e.g. your multi-tasking OS decided to do something else at the same time).
credit: @jamesdlin from the comment section.