naia_shared/backends/native/timer.rs
1use std::time::{Duration, Instant};
2
3/// A Timer with a given duration after which it will enter into a "Ringing"
4/// state. The Timer can be reset at an given time, or manually set to start
5/// "Ringing" again.
6pub struct Timer {
7 duration: Duration,
8 last: Instant,
9}
10
11impl Timer {
12 /// Creates a new Timer with a given Duration
13 pub fn new(duration: Duration) -> Self {
14 Timer {
15 last: Instant::now(),
16 duration,
17 }
18 }
19
20 /// Reset the Timer to stop ringing and wait till 'Duration' has elapsed
21 /// again
22 pub fn reset(&mut self) {
23 self.last = Instant::now();
24 }
25
26 /// Gets whether or not the Timer is "Ringing" (i.e. the given Duration has
27 /// elapsed since the last "reset")
28 pub fn ringing(&self) -> bool {
29 Instant::now().saturating_duration_since(self.last) > self.duration
30 }
31
32 /// Manually causes the Timer to enter into a "Ringing" state
33 pub fn ring_manual(&mut self) {
34 self.last -= self.duration;
35 }
36}