When I was writing the
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.