Skip to content

Commit d6f851a

Browse files
committed
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.
1 parent b6bf94a commit d6f851a

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

crates/bevy_time/src/timer.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,24 @@ impl Timer {
206206
self.tick(remaining);
207207
}
208208

209+
/// Almost finishes the timer leaving 1 ns of remaining time.
210+
/// This can be useful when needing an immediate action without having
211+
/// to wait for the set duration of the timer in the first tick.
212+
///
213+
/// # Examples
214+
/// ```
215+
/// # use bevy_time::*;
216+
/// use std::time::Duration;
217+
/// let mut timer = Timer::from_seconds(1.5, TimerMode::Once);
218+
/// timer.almost_finish();
219+
/// assert!(!timer.is_finished());
220+
/// assert_eq!(timer.remaining(), Duration::from_nanos(1));
221+
/// ```
222+
pub fn almost_finish(&mut self) {
223+
let remaining = self.remaining() - Duration::from_nanos(1);
224+
self.tick(remaining);
225+
}
226+
209227
/// Returns the mode of the timer.
210228
///
211229
/// # Examples
@@ -628,6 +646,21 @@ mod tests {
628646
assert_eq!(t.times_finished_this_tick(), 34);
629647
}
630648

649+
#[test]
650+
fn almost_finished_repeating() {
651+
let mut t = Timer::from_seconds(10.0, TimerMode::Repeating);
652+
let duration = Duration::from_nanos(1);
653+
654+
t.almost_finish();
655+
assert!(!t.is_finished());
656+
assert_eq!(t.times_finished_this_tick(), 0);
657+
assert_eq!(t.remaining(), Duration::from_nanos(1));
658+
659+
t.tick(duration);
660+
assert!(t.is_finished());
661+
assert_eq!(t.times_finished_this_tick(), 1);
662+
}
663+
631664
#[test]
632665
fn paused() {
633666
let mut t = Timer::from_seconds(10.0, TimerMode::Once);

0 commit comments

Comments
 (0)