Prog blog

How to throttle in rust stwdeb

How to throttle in rust stwdeb

When I was writing the Lines game, I wanted to limit the number of calls to drawing the game. In Rust it's not that easy to write, but you can do it quickly with JavaScript.

use stdweb::Value;

#[derive(Debug)]
pub struct Throttle(Value);

impl Throttle {
  pub fn new<F>(callback: F, wait: u32) -> Self
  where
    F: Fn() + 'static,
  {
    Throttle(js!(
        var callback = @{callback};
        var wait = @{wait};

        var state = {
          wait: wait,
          active: false,
          callback: callback,
        };

        return state;
    ))
  }

  pub fn update(&self) {
    js! { @(no_return)
      var state = @{&self.0};
      if (state.active === false) {
        state.active = true;
        setTimeout(() => {
          state.callback();
        }, 0);
        setTimeout(() => {
          state.active = false;
        }, state.wait);
      }
    }
  }
}

Below is the throttle initialization.

let draw_callback = move || {
  // Draw body
};
let draw_throttle = Throttle::new(draw_callback, 1000 / 60);

In draw callback we can include a call to the function responsible for drawing our program. In the example I gave standard 60 FPS.

draw_throttle.update();

The update function is a trigger for throttle, which will call our previously specified callback and the next call will only be made after the specified time.