Prog blog

How to throttle in rust stwdeb

How to throttle in rust stwdeb

When I was writing theLines 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;

pub struct Throttle(Value);

impl Throttle {
  pub fn new<F>(callback: F, wait: u32) -> Self
    F: Fn() + 'static,
        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 ( === false) { = true;
        setTimeout(() => {
        }, 0);
        setTimeout(() => {
 = 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.


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.