-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex41-04.html
77 lines (67 loc) · 1.88 KB
/
ex41-04.html
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
<!DOCTYPE html>
<html>
<body>
<div id="container">
<div id="left">
<pre>일반 클릭 이벤트 카운터 <span class="normal-msg">0</span></pre>
<pre>디바운스 클릭 이벤트 카운터 (delay 1s) <span class="debounce-msg">0</span></pre>
<pre>스로틀 클릭 이벤트 카운터 (delay 1s) <span class="throttle-msg">0</span></pre>
</div>
<div id="right">
<button>click me</button>
</div>
</div>
<script>
const $button = document.querySelector('button');
const $normalMsg = document.querySelector('.normal-msg');
const $debounceMsg = document.querySelector('.debounce-msg');
const $throttleMsg = document.querySelector('.throttle-msg');
const debounce = (callback, delay) => {
let timerId;
return (...args) => {
if (timerId) clearTimeout(timerId);
timerId = setTimeout(callback, delay, ...args);
};
};
const throttle = (callback, delay) => {
let timerId;
return (...args) => {
if (timerId) return;
timerId = setTimeout(() => {
callback(...args);
timerId = null;
}, delay);
};
};
$button.addEventListener('click', () => {
$normalMsg.textContent = +$normalMsg.textContent + 1;
});
const debounceDelay = 1000;
$button.addEventListener('click', debounce(() => {
$debounceMsg.textContent = +$debounceMsg.textContent + 1;
}, debounceDelay));
const throttleDelay = 1000;
$button.addEventListener('click', throttle(() => {
$throttleMsg.textContent = +$throttleMsg.textContent + 1;
}, throttleDelay));
</script>
</body>
<style>
body {
border: 1px solid gray;
border-radius: 25px;
width: 500px;
margin: 300px auto;
padding: 20px;
}
#container {
display: flex;
}
#left {
flex-grow: 1;
}
#right > button {
height: 100%;
}
</style>
</html>