timer_controller/
lib.rs

1#![deny(missing_docs)]
2
3//! A timer controller.
4
5extern crate input;
6
7use input::GenericEvent;
8
9/// A timer relative to start of program.
10pub struct Timer {
11    /// The interval in seconds between each trigger.
12    pub interval: f64,
13    /// The time in seconds from start of program.
14    pub time: f64,
15    /// The time of next trigger in seconds.
16    pub next: f64,
17}
18
19impl Timer {
20    /// Creates a new timer.
21    pub fn new(interval: f64) -> Timer {
22        Timer {
23            interval: interval,
24            time: 0.0,
25            next: 0.0,
26        }
27    }
28
29    /// Calls closure for each interval to catch up with update time.
30    ///
31    /// The timing is inaccurate for less intervals than the update interval.
32    pub fn event<E: GenericEvent, F: FnMut()>(&mut self, e: &E, mut f: F) {
33        if let Some(args) = e.update_args() {
34            self.time = self.time + args.dt;
35            while self.next <= self.time {
36                self.next = self.next + self.interval;
37                f();
38            }
39        }
40    }
41}