-
Notifications
You must be signed in to change notification settings - Fork 0
/
24. Throttle.js
32 lines (25 loc) · 884 Bytes
/
24. Throttle.js
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
// https://www.syncfusion.com/blogs/post/javascript-debounce-vs-throttle.aspx#:~:text=Debounce%20is%20most%20suitable%20for,events%20like%20resizing%20and%20scrolling.
var searchBarDom = document.getElementById('search-bar');
var numberOfKeyPresses = 0;
var numberOfApiCalls = 0;
const getSearchResult = throttle(() => {
numberOfApiCalls += 1;
console.log('Number of API Calls : ' + numberOfApiCalls);
}, 1000);
searchBarDom.addEventListener('input', function (e) {
numberOfKeyPresses += 1;
console.log('Search Keyword : ' + e.target.value);
console.log('Number of Key Presses : ' + numberOfKeyPresses);
getSearchResult();
});
function throttle(callback, delay = 1000) {
let shouldWait = false;
return (...args) => {
if (shouldWait) return;
callback(...args);
shouldWait = true;
setTimeout(() => {
shouldWait = false;
}, delay);
};
}