Dart: Timer
Timer class is a countdown that can be used to schedule a single event or repeated events.
Timer(Duration(seconds: 1), () {
print('Hello, World!');
});
In the previous example we are creating a timer that will execute the function after 1 second. Timers are non-blocking and run on a different thread.
We also can schedule a repeated event:
Timer.periodic(Duration(seconds: 1), (timer) {
print('Hello, World!');
});
In this case, the function will be executed every second.
A timer can be started and canceled:
Timer timer = Timer.periodic(Duration(seconds: 1), (timer) {
print("timer is running");
});
timer.cancel();
🕒 Duration
Duration is a class that represents a time span.
Duration(seconds: 1);
Duration(minutes: 1);
Duration(hours: 1);
Duration(days: 1);
We can apply some math operations to a duration:
var d = Duration(seconds: 30);
d = d + Duration(seconds: 30);
print(d.inMinutes); // 1
Here, we are adding 30 seconds to the duration and then converting it to minutes.
Another example:
var d = Duration(seconds: 30);
d = d * 2;
print(d.inSeconds); // 60
We also can specify the hour, minute, second and millisecond:
var time = Duration(hours: 1, minutes: 30, seconds: 30, milliseconds: 30);
print(time.inSeconds); // 5430
print(time.inMinutes); // 90
print(time.inHours); // 1
print(time.inMilliseconds); // 5430030
And create a negative duration:
var x = Duration(seconds: -30);
var y = Duration(minutes: 1, seconds: 30);
var z = y + x;
print(z.inSeconds); // 60
In the previous example we are creating a negative duration and then adding it to another duration.
Durations can be compared:
var x = Duration(seconds: 30);
var y = Duration(minutes: 1, seconds: 30);
print(x < y); // true
print(x > y); // false
print(x == y); // false
//using compareTo method
print(x.compareTo(y)); // -1
compareTo
: returns -1 if x is shorter than y, 0 if x and y are equal, and 1 if x is longer than y.
StopWatch
Stopwatch is a class that measures elapsed time.
var watch = Stopwatch();
watch.start();
print('Stopwatch started');
for (var i = 0; i < 1000000000; i++) {
//do nothing
}
watch.stop();
print('Stopwatch stopped');
print('Time elapsed: ${watch.elapsedMilliseconds} milliseconds');
// Time elapsed: 246 milliseconds
print('Time elapsed: ${watch.elapsed.inSeconds} seconds');
// Time elapsed: 0 seconds
print('Time elapsed: ${watch.elapsed.inMinutes} minutes');
// Time elapsed: 0 minutes