-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
47 lines (38 loc) · 1014 Bytes
/
index.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const btn = document.querySelector("button");
const logsContainer = document.querySelector("#logs");
const displayLog = (type) => {
logsContainer.innerHTML += `<p>${type}: ${new Date().toLocaleTimeString()}</p>`;
};
const logDebounce = () => {
console.log("Debounced");
displayLog("Debounced");
};
const logThrottle = () => {
console.log("Throttled");
displayLog("Throttled");
};
const debounce = (fn, delay) => {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
};
const throttle = (fn, limit) => {
let flag = true;
return function (...args) {
if (flag) {
fn.apply(this, args);
flag = false;
setTimeout(() => {
flag = true;
}, limit);
}
};
};
const onClickDebounce = debounce(logDebounce, 500);
const onClickThrottle = throttle(logThrottle, 500);
btn.addEventListener("click", onClickDebounce);
btn.addEventListener("click", onClickThrottle);