I am trying to throttle my html on input when user enters some words into search field there must be a redrawing of the block. When I implemented throttle function into my code, the live search stopped working, now the card redrawing does not happen
JavaScript
x
32
32
1
searchInput.addEventListener('input', (event: Event) => {
2
searchTerm = (event.target as HTMLTextAreaElement).value.toLowerCase();
3
throttle(() => {
4
showList();
5
}, 100);
6
});
7
8
function throttle(func: Function, ms: number) {
9
let isThrottled: boolean = false;
10
let savedArgs: any, savedThis: any;
11
12
function wrapper(this: any) {
13
if (isThrottled) {
14
savedArgs = arguments;
15
savedThis = this;
16
return;
17
}
18
func.apply(this, arguments);
19
isThrottled = true;
20
21
setTimeout(() => {
22
isThrottled = false; // (3)
23
if (savedArgs) {
24
wrapper.apply(savedThis, savedArgs);
25
savedArgs = savedThis = null;
26
}
27
}, ms);
28
}
29
30
return wrapper;
31
}
32
Advertisement
Answer
Your throttle
returns a function. You called throttle()
but you didn’t use the function it returns.
You should do something like that
JavaScript
1
31
31
1
const throttledShowList = throttle(showList, 100); // <-- Add this
2
searchInput.addEventListener('input', (event: Event) => {
3
searchTerm = (event.target as HTMLTextAreaElement).value.toLowerCase();
4
throttledShowList(); // <-- Replace the previous throttle() call with this
5
});
6
7
function throttle(func: Function, ms: number) {
8
let isThrottled: boolean = false;
9
let savedArgs: any, savedThis: any;
10
11
function wrapper(this: any) {
12
if (isThrottled) {
13
savedArgs = arguments;
14
savedThis = this;
15
return;
16
}
17
func.apply(this, arguments);
18
isThrottled = true;
19
20
setTimeout(() => {
21
isThrottled = false; // (3)
22
if (savedArgs) {
23
wrapper.apply(savedThis, savedArgs);
24
savedArgs = savedThis = null;
25
}
26
}, ms);
27
}
28
29
return wrapper;
30
}
31
That way, you define a throttled version of your function that you call on input