Skip to main content

tilo_rt/
timer.rs

1//! Waiting without a thread: the sanctioned replacement for
2//! `std::thread::sleep` inside async work.
3
4use std::time::Duration;
5
6/// Wait `duration`, then resolve. Natively this is tokio's timer, so it must
7/// run on a runtime with timers: the app runtime, a daemon or
8/// [`block_on`](crate::block_on). In a page it is one `setTimeout`, which a
9/// background tab may throttle.
10pub async fn sleep(duration: Duration) {
11    imp::sleep(duration).await;
12}
13
14/// The instant the runtime's timers measure against: tokio's clock, which a
15/// test runtime started paused holds still and advances itself. A deadline
16/// that a tokio timer enforces is read on this clock, so the timer and the
17/// expiry check agree however promptly a loaded host runs them.
18#[cfg(not(target_family = "wasm"))]
19#[must_use]
20pub fn timer_now() -> tokio::time::Instant {
21    tokio::time::Instant::now()
22}
23
24#[cfg(not(target_family = "wasm"))]
25mod imp {
26    use std::time::Duration;
27
28    pub(super) async fn sleep(duration: Duration) {
29        tokio::time::sleep(duration).await;
30    }
31}
32
33#[cfg(all(target_family = "wasm", target_os = "unknown"))]
34mod imp {
35    use std::time::Duration;
36
37    use wasm_bindgen::JsCast as _;
38
39    /// The callback owns the sending half, so the future holds no browser
40    /// object and stays `Send`; the closure frees itself when it fires.
41    pub(super) async fn sleep(duration: Duration) {
42        let (fired, wait) = tokio::sync::oneshot::channel::<()>();
43        let armed = {
44            let callback = wasm_bindgen::closure::Closure::once_into_js(move || {
45                let _ = fired.send(());
46            });
47            // `setTimeout` caps delays at 2^31 - 1 ms.
48            #[allow(
49                clippy::cast_precision_loss,
50                reason = "a clamped millisecond count is exact in an f64"
51            )]
52            let millis = duration.as_millis().min(i32::MAX as u128) as f64;
53            let global = js_sys::global();
54            js_sys::Reflect::get(&global, &"setTimeout".into())
55                .ok()
56                .and_then(|set_timeout| set_timeout.dyn_into::<js_sys::Function>().ok())
57                .is_some_and(|set_timeout| {
58                    set_timeout
59                        .call2(&global, &callback, &millis.into())
60                        .is_ok()
61                })
62        };
63        if armed {
64            let _ = wait.await;
65        }
66    }
67}
68
69#[cfg(all(target_family = "wasm", not(target_os = "unknown")))]
70mod imp {
71    use std::time::Duration;
72
73    pub(super) async fn sleep(duration: Duration) {
74        tokio::time::sleep(duration).await;
75    }
76}
77
78#[cfg(test)]
79#[cfg(not(target_family = "wasm"))]
80mod tests {
81    use super::*;
82
83    tilo_test_env::scenario! {
84        fn sleep_waits_on_the_runtime_timer_and_is_send;
85
86        phase sleep_waits_on_the_runtime_timer;
87        {
88            let started = tilo_clock::now();
89            crate::block_on(sleep(Duration::from_millis(30))).unwrap();
90            assert!(started.elapsed() >= Duration::from_millis(30));
91        }
92
93        phase sleep_is_send;
94        {
95            fn send<T: Send>(_: &T) {}
96            send(&sleep(Duration::ZERO));
97        }
98    }
99}