Function debounce
pub fn debounce<T>(
delay: Duration,
cb: impl FnMut(T) + 'static,
) -> impl FnMut(T)where
T: 'static,
Expand description
“Debounce” a callback function. This will cause it to wait for a period of delay
after it is called. If it is called again during that period, it will wait
delay
before running, and so on. This can be used, for example, to wrap event
listeners to prevent them from firing constantly as you type.
use leptos::{leptos_dom::helpers::debounce, logging::log, prelude::*, *};
#[component]
fn DebouncedButton() -> impl IntoView {
let delay = std::time::Duration::from_millis(250);
let on_click = debounce(delay, move |_| {
log!("...so many clicks!");
});
view! {
<button on:click=on_click>"Click me"</button>
}
}
§Note about Context
The callback is called outside of the reactive ownership tree. This means that it does not have access to context via use_context
. If you want to use context inside the callback, you should either call use_context
in the body of the component, and move the value into the callback, or access the current owner inside the component body using Owner::current
and reestablish it in the callback with Owner::with
.