More than 3 years have passed since last update.
RustでWebAssembly: web_sysでasyncなsleepをする
1
Last updated at Posted at 2021-10-08
はじめに
RustでWebAssemblyを作っていて、async な sleep() をするコードです。
コード
以下のような関数を定義して、
use futures::Future;
use js_sys::Promise;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
pub fn sleep(ms: i32) -> impl Future {
let p = Promise::new(&mut |resolve, _| {
web_sys::window()
.unwrap()
.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms)
.unwrap();
});
JsFuture::from(p)
}
こんな感じで使います。
async fn hogehoge() {
sleep(1).await; // sleep 1ms
}
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme
