sauron_core/dom/
time.rs

1use crate::dom::{window, Cmd};
2use futures::channel::mpsc;
3use wasm_bindgen::{prelude::*, JsCast};
4
5/// Provides function related to Time
6#[derive(Clone, Copy)]
7pub struct Time;
8
9impl Time {
10    /// do this task at every `ms` interval
11    pub fn every<F, MSG>(interval_ms: i32, cb: F) -> Cmd<MSG>
12    where
13        F: Fn() -> MSG + 'static,
14        MSG: 'static,
15    {
16        let (mut tx, rx) = mpsc::unbounded();
17        //The web_sys::Event here is undefined, it is just used here to make storing the closure
18        //uniform
19        let closure_cb: Closure<dyn FnMut(web_sys::Event)> = Closure::new(move |_event| {
20            let msg = cb();
21            tx.start_send(msg).unwrap();
22        });
23        window()
24            .set_interval_with_callback_and_timeout_and_arguments_0(
25                closure_cb.as_ref().unchecked_ref(),
26                interval_ms,
27            )
28            .expect("Unable to start interval");
29        Cmd::recurring(rx, closure_cb)
30    }
31}