Skip to main content

bark_runtime/
sleep.rs

1use std::time::Duration;
2
3/// Sleep for the given duration.
4///
5/// On native platforms, uses `tokio::time::sleep`.
6/// On WASM, uses `gloo_timers::future::sleep`.
7pub async fn sleep(duration: Duration) {
8	#[cfg(not(target_arch = "wasm32"))]
9	{
10		tokio::time::sleep(duration).await;
11	}
12
13	#[cfg(target_arch = "wasm32")]
14	{
15		gloo_timers::future::sleep(duration).await;
16	}
17}
18
19#[cfg(test)]
20mod test {
21	use super::*;
22
23	use crate::Instant;
24
25	#[cfg(target_arch = "wasm32")]
26	use wasm_bindgen_test::wasm_bindgen_test;
27	#[cfg(target_arch = "wasm32")]
28	wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
29
30	/// Sleeping returns only once the requested duration has passed.
31	#[cfg_attr(not(target_arch = "wasm32"), tokio::test)]
32	#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
33	async fn sleep_waits_for_the_duration() {
34		let start = Instant::now();
35		sleep(Duration::from_millis(50)).await;
36		assert!(start.elapsed() >= Duration::from_millis(50), "{:?}", start.elapsed());
37	}
38
39	/// A zero-duration sleep returns.
40	#[cfg_attr(not(target_arch = "wasm32"), tokio::test)]
41	#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
42	async fn zero_sleep_returns() {
43		sleep(Duration::ZERO).await;
44	}
45}
46