当将Rust编译为wasm(Web程序集)时,我该如何睡眠10毫秒? [英] When compiling Rust to wasm (web assembly), how can I sleep for 10 milliseconds?

查看:154
本文介绍了当将Rust编译为wasm(Web程序集)时,我该如何睡眠10毫秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的rust程序正在管理2d html canvas上下文的内存,而我试图达到60fps.我可以很容易地计算出每帧之间的增量,结果大约是5毫秒.

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.

我不清楚如何使Rust Webassembly程序在剩余的11毫秒内进入睡眠状态.一种选择是让JavaScript在每个 requestAnimationFrame 上调用Rust并将其用作驱动程序,但我很好奇将其全部保留在Rust中.

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.

在编译到wasm目标时,我正在有效地寻找JavaScript的 setTimeout(renderNext,11)

I'm effectively looking for the Rust equivalent of JavaScript's setTimeout(renderNext, 11) when compiling out to the wasm target.

推荐答案

当编译到wasm目标时,我正在有效地寻找JavaScript的 setTimeout(renderNext,11)

I'm effectively looking for the Rust equivalent of JavaScript's setTimeout(renderNext, 11) when compiling out to the wasm target.

有多个Rust板条箱已绑定到JavaScript Web API,最著名的是 web-sys .看看其中一个文档 setTimeout 重载.

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.

这实际上不是Rust的等效项,因为它直接调用了JS函数.但是您将无法解决:休眠或获取当前时间都是主机环境必须提供的功能.不能仅使用原始语言来实现它们.

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.

一种选择是让JavaScript在每个 requestAnimationFrame 上调用Rust,并将其用作驱动程序,但我很好奇将其全部保留在Rust中.

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.

是的,您应该使用 requestAnimationFrame (链接到 web-sys 文档).这比您自己定时更可取.尤其是,这种方法也将暂停调用代码时的标签是不活动之类的东西.在桌面环境中,您可以执行以下操作:要求主机环境(即操作系统,通常通过OpenGL等)将程序与屏幕刷新同步.

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.

这篇关于当将Rust编译为wasm(Web程序集)时,我该如何睡眠10毫秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆