While loop stops Timer from running (Dart)

Viewed 283

I have a question about while loop in dart.

This is a piece of code:

bool temp = false;
Timer(Duration(milliseconds: 5), () {
    print('In timer:' + temp.toString());
    temp = true;
});
Timer(Duration(milliseconds: 1000), () {
    print('In timer:' + temp.toString());
});

The result is exactly what I expect:

false (after 5 ms)
true (after 1 s)

But when add while loop:

bool temp = false;
Timer(Duration(milliseconds: 5), () {
    print('In timer:' + temp.toString());
    temp = true;
});

while (!temp) {}
print('End');

I expect that it will print out the console like this:

false
End (immediately after false)

But everything stucks in while loop and the timer doesn't seem to run to update temp anymore. May I get any explanation?

1 Answers

Your while loop and timer are running in the same isolate, so your while loop blocks the event loop which prevents the timer from executing.

To learn more about the event loop and isolates, see the official blog post or an old but detailed article.

Related