pub struct Timer {
pub created: Instant,
pub last_run: Option<Instant>,
pub delay: Option<Duration>,
pub interval: Option<Duration>,
pub timeout: Option<Duration>,
pub callback: TimerCallback,
}
Expand description
A Timer
is a function that is run on every frame.
There are often a lot of visual tasks such as animations or fetching the next frame for a GIF or video, etc. - that need to run every frame or every X milliseconds, but they aren’t heavy enough to warrant creating a thread - otherwise the framework would create too many threads, which leads to a lot of context switching and bad performance.
The callback of a Timer
should be fast enough to run under 16ms,
otherwise running timers will block the main UI thread.
Fields§
§created: Instant
Stores when the timer was created (usually acquired by Instant::now()
)
last_run: Option<Instant>
When the timer was last called (None
only when the timer hasn’t been called yet).
delay: Option<Duration>
If the timer shouldn’t start instantly, but rather be delayed by a certain timeframe
interval: Option<Duration>
How frequently the timer should run, i.e. set this to Some(Duration::from_millis(16))
to run the timer every 16ms. If this value is set to None
, (the default), the timer
will execute the timer as-fast-as-possible (i.e. at a faster framerate
than the framework itself) - which might be performance intensive.
timeout: Option<Duration>
When to stop the timer (for example, you can stop the
execution after 5s using Some(Duration::from_secs(5))
).
callback: TimerCallback
Callback to be called for this timer
Implementations§
Source§impl Timer
impl Timer
Sourcepub fn new(callback: TimerCallbackType) -> Self
pub fn new(callback: TimerCallbackType) -> Self
Create a new timer
Sourcepub fn with_delay(self, delay: Duration) -> Self
pub fn with_delay(self, delay: Duration) -> Self
Delays the timer to not start immediately but rather start after a certain time frame has elapsed.
Sourcepub fn with_interval(self, interval: Duration) -> Self
pub fn with_interval(self, interval: Duration) -> Self
Converts the timer into a timer, running the function only
if the given Duration
has elapsed since the last run
Sourcepub fn with_timeout(self, timeout: Duration) -> Self
pub fn with_timeout(self, timeout: Duration) -> Self
Converts the timer into a countdown, by giving it a maximum duration (counted from the creation of the Timer, not the first use).
Sourcepub fn invoke<'a>(&mut self, info: TimerCallbackInfo<'a>) -> TimerCallbackReturn
pub fn invoke<'a>(&mut self, info: TimerCallbackInfo<'a>) -> TimerCallbackReturn
Crate-internal: Invokes the timer if the timer and
the self.timeout
allow it to