diff --git a/crates/bevy_app/src/schedule_runner.rs b/crates/bevy_app/src/schedule_runner.rs index 6d10c92d76..ea0f23265d 100644 --- a/crates/bevy_app/src/schedule_runner.rs +++ b/crates/bevy_app/src/schedule_runner.rs @@ -159,9 +159,8 @@ impl Plugin for ScheduleRunnerPlugin { } else { loop { match tick(&mut app, wait) { - Ok(Some(_delay)) => { - #[cfg(feature = "std")] - std::thread::sleep(_delay); + Ok(Some(delay)) => { + bevy_platform_support::thread::sleep(delay); } Ok(None) => continue, Err(exit) => return exit, diff --git a/crates/bevy_platform_support/src/lib.rs b/crates/bevy_platform_support/src/lib.rs index eada254595..96f2f9a21c 100644 --- a/crates/bevy_platform_support/src/lib.rs +++ b/crates/bevy_platform_support/src/lib.rs @@ -17,6 +17,7 @@ extern crate alloc; pub mod hash; pub mod sync; +pub mod thread; pub mod time; #[cfg(feature = "alloc")] diff --git a/crates/bevy_platform_support/src/thread.rs b/crates/bevy_platform_support/src/thread.rs new file mode 100644 index 0000000000..e1d593c90b --- /dev/null +++ b/crates/bevy_platform_support/src/thread.rs @@ -0,0 +1,29 @@ +//! Provides `sleep` for all platforms. + +pub use thread::sleep; + +cfg_if::cfg_if! { + // TODO: use browser timeouts based on ScheduleRunnerPlugin::build + if #[cfg(feature = "std")] { + use std::thread; + } else { + mod fallback { + use core::{hint::spin_loop, time::Duration}; + + use crate::time::Instant; + + /// Puts the current thread to sleep for at least the specified amount of time. + /// + /// As this is a `no_std` fallback implementation, this will spin the current thread. + pub fn sleep(dur: Duration) { + let start = Instant::now(); + + while start.elapsed() < dur { + spin_loop() + } + } + } + + use fallback as thread; + } +} diff --git a/crates/bevy_platform_support/src/time/fallback.rs b/crates/bevy_platform_support/src/time/fallback.rs index 344fe74baf..c438e6e379 100644 --- a/crates/bevy_platform_support/src/time/fallback.rs +++ b/crates/bevy_platform_support/src/time/fallback.rs @@ -80,7 +80,7 @@ impl Instant { /// Returns the amount of time elapsed since this instant. #[must_use] pub fn elapsed(&self) -> Duration { - self.saturating_duration_since(Instant::now()) + Instant::now().saturating_duration_since(*self) } /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as