wayrs_utils/
timer.rs

1use std::time::{Duration, Instant};
2
3/// A simple timer. Useful for keyboard-repeat.
4#[derive(Debug)]
5pub struct Timer {
6    next_fire: Instant,
7    interval: Duration,
8}
9
10impl Timer {
11    /// Create a new timer with a given delay and interval.
12    #[must_use]
13    pub fn new(delay: Duration, interval: Duration) -> Self {
14        Self {
15            next_fire: Instant::now() + delay,
16            interval,
17        }
18    }
19
20    /// Update the internal state and check if timer fired.
21    ///
22    /// Returns `true` if timer has fired. `false` otherwise.
23    ///
24    /// Regularly call thin function in your event loop.
25    pub fn tick(&mut self) -> bool {
26        let now = Instant::now();
27        if now >= self.next_fire {
28            self.next_fire += self.interval;
29            true
30        } else {
31            false
32        }
33    }
34
35    /// The duration untill next fire.
36    #[must_use]
37    pub fn sleep(&self) -> Duration {
38        self.next_fire.saturating_duration_since(Instant::now())
39    }
40}