This code delays an event for a given number of milliseconds. The code starts by checking to see if the delay value, which is in milliseconds, is zero. If it is not zero, the code panics. It then creates a duration, in milliseconds, and sets the target time to the current time. It then creates an interval, in milliseconds, and repeats the loop. Each time the loop runs, it checks to see if the current time has gone beyond the target time. If it has, it sleeps for the given number of milliseconds. Finally, it subtracts the current time from the target time to get the delay in milliseconds.

    use std::{thread::sleep, time::{Duration, Instant}};
    pub fn delay(delay_ms: u64) {
      if delay_ms == 0 {
        panic!("Delay value cannot be 0!");
      let interval = Duration::from_millis(100);
      let target = Duration::from_millis(delay_ms);
      let now = Instant::now();
      let mut next_time = now + interval;
      loop {
        if now.elapsed() >= target {
          // println!("Delayed for {} ms", Instant::now().duration_since(now).as_millis());
        sleep(next_time - Instant::now());
        next_time += interval;
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.