1

I am trying to build small application with Yew (Rustwasm) . I would like to put sleep function in Yew app.when I use use std::thread::sleep , I am getting below error

I am using sleep as below

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)
vallentin
  • 23,478
  • 6
  • 59
  • 81
Naveen
  • 109
  • 1
  • 6
  • The error is pretty self-explanatory, you can't. – vallentin Dec 30 '20 at 20:41
  • Related: [When compiling Rust to wasm (web assembly), how can I sleep for 10 milliseconds?](https://stackoverflow.com/questions/57765987/when-compiling-rust-to-wasm-web-assembly-how-can-i-sleep-for-10-milliseconds) – vallentin Dec 30 '20 at 20:41
  • is there anyway bring sleep functionality before rendering the components in Yew apps ? – Naveen Dec 30 '20 at 20:42
  • It's really nice that you get the `'can't sleep'` message. I'm using WASM with a pure JS frontend and just get the stack trace.. does anybody know how to get these messages too? – User Oct 07 '21 at 06:41

1 Answers1

2

The methods like thread::sleep doesn't work, because in the JS environment you have a single thread only. If you call that sleep you will block the app completely.

If you want to use an interval you should "order" a callback. You can check the following example how to use TimeoutService or IntervalService for that: yew/examples/timer

The core idea to create a service this way:

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);

Now you can use handler of Msg::Done to react to that timer elapsed.

Threads are actually available, but it's a complex topic and you have to use Web Workers API reach them. Anyway it's useless for your case. Also there are some proposals in standards, but they aren't available in the browsers yet.

DenisKolodin
  • 13,501
  • 3
  • 62
  • 65