In this video, we will use durations to
create an ergonomic timer struct. Our
timing code in our progress code is all
mixed up together, we need to add some
more timing code, so this is probably a
good point to stop and move our timing
code out into a nice timer struct. If
we're going to make a timer,
we're gonna need duration, so let's
import that first. Next let's go down to
the bottom of the file and create our
timer struct there. So we'll begin with
struct timer, and our first field will be
last instant, we'll use it in just the
same way we did in the loop above. Our
second field will be our delta duration,
we'll use this to store the value of now
- last instant. Next, we'll store period
which is also a duration, indicating how
often we want the timer to go off, or be
ready. Our next field will be countdown,
another duration to keep track of how
much time until the timer goes off next.
And our final field will be ready, a
boolean to indicate that the timer is
ready, it's gone off. And now we're ready
to go implement the struct. We're only
going to need one associated function
and one method. Let's follow convention
and name our associated function new to
create a new timer, we'll create now
which will be an instant that's right
now, and we'll use that to populate some
of our fields. Our tail expression here
will just be our instantiated struct.
We'll set last instant to now, Delta to
the durations default which is zero
period let's set that to one second. You
can play around with this if you want to
see different timings,
countdown will also set to zero via the
default, and then ready will set to true
because we want to get immediate
progress output on our first read. Now we
can move on to our one and only method,
update. We'll need a mutable reference to
self so that we can update the fields.
The first thing we need to do is to get
an instant representing right now, and
then we can use that to calculate the
delta and store that in the delta field.
Then we can update the last instant
field to be now. Now we can decrement our
countdown and see if the timer is ready.
Durations can't be negative so we need
to use checked subtraction to return a
result, depending on whether we succeed
at doing the subtraction or overflow to
under zero, meaning we're ready,
so we'll map an error to a closure the
sets ready to true, and then resets the
countdown back to the period value, add a
final semicolon and that's all we need
to do, we are ready to use this timer
struct. In the next video,
using timer we will output progress
statistics at a steady rate.