pub fn use_timeout<Args: 'static, MaybeAsync: SpawnIfAsync<Marker>, Marker>(
duration: Duration,
callback: impl FnMut(Args) -> MaybeAsync + 'static,
) -> UseTimeout<Args>Expand description
A hook to run a callback after a period of time.
Timeouts allow you to trigger a callback that occurs after a period of time. Unlike a debounce, a timeout will not reset it’s timer when triggered again. Instead, calling a timeout while it is already running will start another instance to run the callback after the provided period.
This hook is similar to the web setTimeout() API.
§Examples
Example of using a timeout:
use dioxus::prelude::*;
use dioxus_time::use_timeout;
use std::time::Duration;
#[component]
fn App() -> Element {
// Create a timeout for two seconds.
// Once triggered, this timeout will print "timeout called" after two seconds.
let timeout = use_timeout(Duration::from_secs(2), |()| println!("timeout called"));
rsx! {
button {
onclick: move |_| {
// Trigger the timeout.
timeout.action(());
},
"Click!"
}
}
}§Cancelling Timeouts
Example of cancelling a timeout. This is the equivalent of a debounce.
use dioxus::prelude::*;
use dioxus_time::{use_timeout, TimeoutHandle};
use std::time::Duration;
#[component]
fn App() -> Element {
let mut current_timeout: Signal<Option<TimeoutHandle>> = use_signal(|| None);
let timeout = use_timeout(Duration::from_secs(2), move |()| {
current_timeout.set(None);
println!("timeout called");
});
rsx! {
button {
onclick: move |_| {
// Cancel any currently running timeouts.
if let Some(handle) = *current_timeout.read() {
handle.cancel();
}
// Trigger the timeout.
let handle = timeout.action(());
current_timeout.set(Some(handle));
},
"Click!"
}
}
}§Async Timeouts
Timeouts can accept an async callback:
use dioxus::prelude::*;
use dioxus_time::use_timeout;
use std::time::Duration;
#[component]
fn App() -> Element {
// Create a timeout for two seconds.
// We use an async sleep to wait an even longer duration after the timeout is called.
let timeout = use_timeout(Duration::from_secs(2), |()| async {
println!("Timeout after two total seconds.");
tokio::time::sleep(Duration::from_secs(2)).await;
println!("Timeout after four total seconds.");
});
rsx! {
button {
onclick: move |_| {
// Trigger the timeout.
timeout.action(());
},
"Click!"
}
}
}