wasm_game_lib/
system.rs

1use std::time::Duration;
2use js_sys::{Promise};
3use web_sys::{window};
4use wasm_bindgen_futures::JsFuture;
5use wasm_bindgen::prelude::*;
6
7
8/// This is the wasm version of the sleep function.
9/// For now it is the only way to sleep.
10/// The precision of this function is 1ms.
11pub async fn sleep(duration: Duration) {
12    let promise = Promise::new(&mut |yes, _| {
13        window().unwrap().set_timeout_with_callback_and_timeout_and_arguments_0(&yes, duration.as_millis() as i32).unwrap();
14    });
15    let js_fut = JsFuture::from(promise);
16    js_fut.await.unwrap();
17}
18
19#[wasm_bindgen]
20extern "C" {
21    #[wasm_bindgen(js_namespace = console)]
22    pub fn log(s: &str);
23
24    #[wasm_bindgen(js_namespace = console)]
25    pub fn error(s: &str);
26}
27
28#[macro_export]
29/// A println-like macro. 
30/// **Warning**: This is very slow.
31macro_rules! log {
32    ($($t:tt)*) => ($crate::system::log(&format_args!($($t)*).to_string()))
33}
34
35#[macro_export]
36/// A eprintln-like macro.
37/// **Warning**: This is **extremely** slow.
38macro_rules! elog {
39    ($($t:tt)*) => ($crate::system::error(&format_args!($($t)*).to_string()))
40}