Skip to main content

Module timer

Module timer 

Source
Expand description

Timers that run between frames, on the clock their App keeps.

after runs a closure once, every runs it repeatedly until the returned TimerHandle is dropped or the owner the timer was created under is cleaned up. Both read the app’s clock, not the system clock, so a test that runs the app on a VirtualClock advances time by hand and observes the exact timers it expects, without sleeping.

A timer is registered under the owner that is current when it is created, which is what makes the app find it: every owner chain leads to a root, and the root holds the timer book. Code that runs with no current owner, such as a bare test, creates no timer at all.

use std::time::Duration;

use smudge_core::app::{App, AppConfig, RepaintMode};
use smudge_core::geometry::{Color, Size};
use smudge_core::reactive::{prelude::*, signal_local};
use smudge_core::timer::{self, VirtualClock};
use smudge_core::widget::panel;
use web_time::Instant;

let clock = VirtualClock::new(Instant::now());
let (fired, set_fired) = signal_local(false);
let mut app = App::with_clock(
    AppConfig {
        viewport: Size {
            width: 100.0,
            height: 60.0,
        },
        scale: 1.0,
        clear_color: Color::WHITE,
        repaint: RepaintMode::Damage,
    },
    clock.clone().into(),
    || {
        timer::after(Duration::from_millis(40), move || set_fired.set(true));
        panel()
    },
);

// The timer has not run yet: only the passage of time runs it.
clock.advance(Duration::from_millis(39));
app.frame();
assert!(!fired.get(), "the timer is not due yet");

clock.advance(Duration::from_millis(1));
app.frame();
assert!(fired.get(), "the timer ran when its time was up");

Structs§

Clock
The clock an App and its timers read the time from.
TimerHandle
A handle that cancels its timer when it is dropped.
VirtualClock
A clock whose time moves only when it is advanced.

Functions§

after
Runs fun once, after duration has passed on the app’s clock.
every
Runs fun every period on the app’s clock, until the returned handle is dropped or the creating owner is cleaned up.
now
Returns the current time of the clock of the app that owns the code running right now, or the system time when no app does.