From d6f851a73e31083af797babaa14ffea0987d036c Mon Sep 17 00:00:00 2001 From: Rajveer Date: Sun, 30 Nov 2025 16:59:18 +0530 Subject: [PATCH] Add a new `almost_finish` method for `Timer` with immediate first `tick` action Resolves #21860 This new method would tick the timer by `duration - 1 ns` leaving a very short waiting time for the first tick initiated by the user allowing immediate action. --- crates/bevy_time/src/timer.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/crates/bevy_time/src/timer.rs b/crates/bevy_time/src/timer.rs index bbf76aa1d93a6..696a6a316d521 100644 --- a/crates/bevy_time/src/timer.rs +++ b/crates/bevy_time/src/timer.rs @@ -206,6 +206,24 @@ impl Timer { self.tick(remaining); } + /// Almost finishes the timer leaving 1 ns of remaining time. + /// This can be useful when needing an immediate action without having + /// to wait for the set duration of the timer in the first tick. + /// + /// # Examples + /// ``` + /// # use bevy_time::*; + /// use std::time::Duration; + /// let mut timer = Timer::from_seconds(1.5, TimerMode::Once); + /// timer.almost_finish(); + /// assert!(!timer.is_finished()); + /// assert_eq!(timer.remaining(), Duration::from_nanos(1)); + /// ``` + pub fn almost_finish(&mut self) { + let remaining = self.remaining() - Duration::from_nanos(1); + self.tick(remaining); + } + /// Returns the mode of the timer. /// /// # Examples @@ -628,6 +646,21 @@ mod tests { assert_eq!(t.times_finished_this_tick(), 34); } + #[test] + fn almost_finished_repeating() { + let mut t = Timer::from_seconds(10.0, TimerMode::Repeating); + let duration = Duration::from_nanos(1); + + t.almost_finish(); + assert!(!t.is_finished()); + assert_eq!(t.times_finished_this_tick(), 0); + assert_eq!(t.remaining(), Duration::from_nanos(1)); + + t.tick(duration); + assert!(t.is_finished()); + assert_eq!(t.times_finished_this_tick(), 1); + } + #[test] fn paused() { let mut t = Timer::from_seconds(10.0, TimerMode::Once);