rust - 如何在 Yew 应用程序中包含睡眠功能?
问题描述
我正在尝试使用 Yew (Rustwasm) 构建小型应用程序。我想在 Yew 应用程序中添加睡眠功能。当我使用 use std::thread::sleep 时,出现以下错误
我正在使用如下睡眠
let mut index = 0;
sleep(Duration::new(1, 0));
if col < 3 {
index = row * 4 + (col + 1);
if self.cellule[index].value == 1 {
sleep(Duration::new(1, 0));
wasm.js:314 panicked at 'can't sleep', src/libstd/sys/wasm/thread.rs:26:9
Stack:
Error
at imports.wbg.__wbg_new_59cb74e423758ede (http://127.0.0.1:8080/wasm.js:302:19)
at console_error_panic_hook::hook::hd38f373f442d725c (http://127.0.0.1:8080/wasm_bg.wasm:wasm-function[117]:0x16a3e)
at core::ops::function::Fn::call::hf1476807b3d9587d (http://127.0.0.1:8080/wasm_bg.wasm:wasm-function[429]:0x22955)
at std::panicking::rust_panic_with_hook::hb07b303a83b6d242 (http://127.0.0.1:8080/wasm_bg.wasm:wasm-function[211]:0x1ed0d)
at std::panicking::begin_panic::h97f15f2442acdda4 (http://127.0.0.1:8080/wasm_bg.wasm:wasm-function[321]:0x21ee0)
at std::sys::wasm::thread::Thread::sleep::hdd97a2b229644713 (http://127.0.0.1:8080/wasm_bg.wasm:wasm-function[406]:0x22829)
解决方案
像这样的方法thread::sleep
不起作用,因为在 JS 环境中你只有一个线程。如果您睡觉,您将完全阻止该应用程序。
如果你想使用一个间隔,你应该“订购”一个回调。您可以查看以下示例如何使用TimeoutService
或IntervalService
为此:yew/examples/timer
以这种方式创建服务的核心思想:
let handle = TimeoutService::spawn(
Duration::from_secs(3),
self.link.callback(|_| Msg::Done),
);
// Keep the task or timer will be cancelled
self.timeout_job = Some(handle);
现在,您可以使用 handler ofMsg::Done
对已过的计时器做出反应。
线程实际上是可用的,但这是一个复杂的主题,您必须使用
Web Workers API
. 无论如何,这对您的情况没有用。标准中也有一些建议,但它们还没有在浏览器中可用。
推荐阅读
- python - 如何从 URL 读取图像(urllib.error.HTTPError:HTTP 错误 403:禁止)
- c# - 访问另一个脚本变量,但不能更改游戏内
- reactjs - 开玩笑测试给出错误“无法读取未定义的属性‘createElement’”
- python - Go/Python 异步桥接
- c - 如何解决 C 程序 int main 错误
- opengl - 在相机后面的位置进行广告牌时的伪影
- php - 当数组中有数组时,str_replace 是否完成?
- amazon-web-services - 替换从 VAST 代码返回的多个 HLS VOD 片段
- blogger - 如何检查延迟加载脚本是否适用于 Blogger 帖子中上传的图像?
- django - 在 Django 中验证复杂的关系