web_async/time.rs
1//! Portable async time: `tokio::time` on native, [`wasmtimer`] in the browser.
2//!
3//! Code that sleeps, ticks on an interval, or reads an `Instant` needs to work
4//! on both targets. Native tokio's clock is `std::time::Instant::now()`, which
5//! panics on `wasm32-unknown-unknown` (no clock), and its timers need a runtime
6//! time driver that `wasm_bindgen_futures::spawn_local` doesn't provide. So in
7//! the browser we route through `wasmtimer`, which implements the same API on
8//! `performance.now()` + `setTimeout`. Use `web_async::time` in place of
9//! `tokio::time` and the same code runs on both.
10//!
11//! The surface mirrors `tokio::time` 1:1. The mockable test clock
12//! (`tokio::time::pause`/`advance`) is intentionally not re-exported: it lives
13//! behind tokio's `test-util` feature, which must not leak into normal builds,
14//! and it only ever runs in native tests anyway.
15
16pub use std::time::Duration;
17
18// wasi has a real clock and tokio support, so it goes with native (matching the
19// cfg split in `spawn`).
20#[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
21pub use tokio::time::{
22 interval, interval_at, sleep, sleep_until, timeout, timeout_at, Instant, Interval, MissedTickBehavior, Sleep,
23 Timeout,
24};
25
26#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
27pub use wasmtimer::{
28 std::Instant,
29 tokio::{
30 interval, interval_at, sleep, sleep_until, timeout, timeout_at, Interval, MissedTickBehavior, Sleep, Timeout,
31 },
32};