-
Notifications
You must be signed in to change notification settings - Fork 0
/
debounce.html
58 lines (48 loc) · 1.64 KB
/
debounce.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
<html>
<body>
<button id="debounce">Debounce</button>
<input type="text" id="searchBox" onkeyup="handleKeyUp(event, 'hi')" />
<script>
function fetchData(event, ka) {
const val = event.target.value;
console.log(val, ka);
}
// const handleKeyUp = myDebounce(fetchData, 1000);
const handleKeyUp = myThrottle(fetchData, 1000);
//debounce
function myDebounce(functionToRun, delay) {
let timer;
return function (...args) {
console.log("args", args)
clearTimeout(timer);
timer = setTimeout(() => { functionToRun.call(this, ...args) }, delay)
}
// let timer;
// return function() {
// console.log("arguments", arguments)
// clearTimeout(timer);
// timer = setTimeout(() => functionToRun.apply(this, arguments), delay);
// }
}
//throttle
function myThrottle(functionToRun, delay) {
let flag = true;
return function (...args) {
if (flag) {
flag = false;
functionToRun.call(this, ...args);
setTimeout(() => { flag = true }, delay)
}
}
// let flag = true;
// return function() {
// if (flag) {
// functionToRun.apply(this, arguments);
// flag = false;
// setTimeout(() => { flag=true }, delay);
// }
// }
}
</script>
</body>
</html>