async_sleep_aki/
lib.rs

1/*!
2It provides simple `async_sleep()` that work well in both web browsers and native applications.
3This can be used in the `dioxus` application.
4
5## Howto use
6Just call `async_sleep()` on the frontend or backend.
7
8```rust
9# use async_sleep_aki::async_sleep;
10# async fn func() {
11async_sleep(100).await;
12# }
13```
14
15In dioxus component:
16
17```rust
18use dioxus::prelude::*;
19use async_sleep_aki::delayed_call;
20
21#[component]
22fn func() -> Element {
23    let mut is_loading = use_signal(|| false);
24    use_effect(move ||{
25        spawn(delayed_call(2000, async move {
26            if *is_loading.read() {
27                is_loading.set(false);
28            }
29        }));
30    });
31    rsx!{ div{} }
32}
33```
34
35## Implementation
36If `target` is `wasm32-unknown-unknown`, calls `gloo_timers::future::sleep()`, otherwise calls `tokio::time::sleep()`.
37*/
38
39/// Stops processing for `delay` milliseconds.
40///
41/// Other asynchronous functions will be processed while it is stopped.
42///
43/// If `delay` is a negative number, it is treated as `0` seconds.
44///
45/// In a web browser, this is implemented using the `setTimeout()` function of `javascript`, so it is subject to [the same restrictions].
46///
47/// [the same restrictions]: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#maximum_delay_value
48pub async fn async_sleep(delay: i32) {
49    let delay = if delay >= 0 { delay as u64 } else { 0 };
50    let dur = std::time::Duration::from_millis(delay);
51
52    // for non browser
53    #[cfg(not(all(
54        target_arch = "wasm32",
55        target_vendor = "unknown",
56        target_os = "unknown"
57    )))]
58    tokio::time::sleep(dur).await;
59
60    // for browser
61    #[cfg(all(
62        target_arch = "wasm32",
63        target_vendor = "unknown",
64        target_os = "unknown"
65    ))]
66    gloo_timers::future::sleep(dur).await;
67}
68
69/// Pause processing for `delay` milliseconds and then call the argument async function.
70pub async fn delayed_call<F>(delay: i32, f: F)
71where
72    F: std::future::Future<Output = ()> + 'static,
73{
74    async_sleep(delay).await;
75    f.await;
76}