use_throttle_fn
Throttle execution of a function. Especially useful for rate limiting execution of handlers on events like resize and scroll.
Throttle is a spring that throws balls: After a ball flies out it needs some time to shrink back, so it cannot throw any more balls until it’s ready.
Demo
Usage
use leptos::prelude::*;
use leptos_use_fn_debounce_throttle::use_throttle_fn;
#[component]
fn Demo() -> impl IntoView {
let mut throttled_fn = use_throttle_fn(
|| {
// do something, it will be called at most 1 time per second
},
1000.0,
);
view! {
<button on:click=move |_| { throttled_fn(); }>
"Smash me!"
</button>
}
}
Please note that if the current component is cleaned up before the throttled callback is called, the throttled callback will not be called.
You can provide options when you use use_throttle_fn_with_options.
use leptos::prelude::*;
use leptos_use_filters::ThrottleOptions;
use leptos_use_fn_debounce_throttle::use_throttle_fn_with_options;
#[component]
fn Demo() -> impl IntoView {
let throttled_fn = use_throttle_fn_with_options(
|| {
// do something, it will be called at most 1 time per second
},
1000.0,
ThrottleOptions::default()
.leading(true)
.trailing(true),
);
view! { }
}
If you want to throttle a function that takes an argument there are also the versions
use_throttle_fn_with_arg and use_throttle_fn_with_arg_and_options.
SendWrapped Return
The returned closure is a sendwrapped function. It can
only be called from the same thread that called use_throttle_....
Recommended Reading
Server-Side Rendering
Make sure you follow the instructions in Server-Side Rendering.
Internally this uses setTimeout which is not supported on the server. So usually calling
a throttled function on the server will simply be ignored.
Installation
cargo add leptos-use-fn-debounce-throttle
Options
ThrottleOptions
Every option is set with a builder method of the same name, e.g. ThrottleOptions::default().trailing(...). See also the API docs.
trailing
Type: bool
Invoke on the trailing edge of the timeout. Defaults to true.
leading
Type: bool
Invoke on the leading edge of the timeout (=immediately). Defaults to true.