Skip to main content

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#[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
19pub use std::time::{SystemTime, SystemTimeError, UNIX_EPOCH};
20
21// wasi has a real clock and tokio support, so it goes with native (matching the
22// cfg split in `spawn`).
23#[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
24pub use tokio::time::{
25	error::Elapsed, interval, interval_at, sleep, sleep_until, timeout, timeout_at, Instant, Interval,
26	MissedTickBehavior, Sleep, Timeout,
27};
28
29#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
30pub use wasmtimer::{
31	std::{Instant, SystemTime, SystemTimeError, UNIX_EPOCH},
32	tokio::{
33		error::Elapsed, interval, interval_at, sleep, sleep_until, timeout, timeout_at, Interval, MissedTickBehavior,
34		Sleep, Timeout,
35	},
36};