My rust program is managing memory for a 2d html canvas context, and I'm trying to hit ~60fps. I can calculate the delta between each frame easily, and it turns out to be roughly ~5ms.
I'm unclear on how to put my Rust webassembly program to sleep for the remaining 11ms. One option would be to have JavaScript call into Rust on every requestAnimationFrame
and use that as the driver, but I'm curious to keep it all in Rust if possible.
I'm effectively looking for the Rust equivalent of JavaScript's setTimeout(renderNext, 11)
when compiling out to the wasm target.
I'm effectively looking for the Rust equivalent of JavaScript's
setTimeout(renderNext, 11)
when compiling out to the wasm target.
There are several Rust crates that have bindings to the JavaScript web API, most notably web-sys
. Take a look at the documentation for one of the setTimeout
overloads.
This is not really a Rust equivalent though, as it pretty directly calls the JS function. But you won't be able to get around that: sleeping or getting the current time are both functions that the host environment has to offer. They cannot be implemented in the raw language alone.
One option would be to have JavaScript call into Rust on every
requestAnimationFrame
and use that as the driver, but I'm curious to keep it all in Rust if possible.
Yes, you should use requestAnimationFrame
(link to web-sys
docs). This is much preferred over timing it yourself. In particular, this method will also pause calling your code when the tab is not active and stuff like that. In a desktop environment you would do the same: ask the host environment (i.e. the operating system, often via OpenGL or so) to synchronize your program to screen refreshes.