1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
use std::rc::Rc;
use yew::prelude::*;
use super::{use_mut_latest, use_timeout};
pub struct UseThrottleHandle {
run: Rc<dyn Fn()>,
cancel: Rc<dyn Fn()>,
}
impl UseThrottleHandle {
pub fn run(&self) {
(self.run)();
}
pub fn cancel(&self) {
(self.cancel)();
}
}
impl Clone for UseThrottleHandle {
fn clone(&self) -> Self {
Self {
run: self.run.clone(),
cancel: self.cancel.clone(),
}
}
}
#[hook]
pub fn use_throttle<Callback>(callback: Callback, millis: u32) -> UseThrottleHandle
where
Callback: FnMut() + 'static,
{
let throttled = use_mut_ref(|| false);
let callback_ref = use_mut_latest(callback);
let timeout = {
let throttled = throttled.clone();
use_timeout(
move || {
*throttled.borrow_mut() = false;
},
millis,
)
};
let run = {
let throttled = throttled.clone();
let timeout = timeout.clone();
Rc::new(move || {
let throttled_value = *throttled.borrow();
if !throttled_value {
let callback_ref = callback_ref.current();
let callback = &mut *callback_ref.borrow_mut();
callback();
*throttled.borrow_mut() = true;
timeout.reset();
}
})
};
let cancel = {
Rc::new(move || {
timeout.cancel();
*throttled.borrow_mut() = false;
})
};
UseThrottleHandle { run, cancel }
}