1use std::time::{Duration, Instant};
2
3pub struct Timer {
4 pub countdown: Duration,
5 pub delta: Duration,
6 pub last_instant: Instant,
7 pub period: Duration,
8 pub ready: bool,
9 pub start: Instant,
10}
11
12impl Timer {
13 pub fn new(resolution_ms: u64) -> Self {
14 let now = Instant::now();
15 Self {
16 countdown: Duration::default(),
17 delta: Duration::default(),
18 last_instant: now,
19 period: Duration::from_millis(resolution_ms),
20 ready: true,
21 start: Instant::now(),
22 }
23 }
24
25 pub fn update(&mut self) {
26 let now = Instant::now();
27
28 self.delta = now - self.last_instant;
29 self.last_instant = now;
30 self.countdown = self.countdown.checked_sub(self.delta).unwrap_or_else(|| {
31 self.ready = true;
32 self.period
33 })
34 }
35}