forked from YvetteLau/Blog
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebounce.html
More file actions
84 lines (77 loc) · 2.42 KB
/
debounce.html
File metadata and controls
84 lines (77 loc) · 2.42 KB
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
78
79
80
81
82
83
84
<!DOCTYPE html>
<html>
<head lang="zh-CN">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title></title>
<style>
.base {
height: 200px;
width: 200px;
background: pink;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
p {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
</style>
</head>
<body>
<div class="base">
<p>点击触发事件</p>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
<script>
window.onload = function () {
function debounce(func, wait, immediate = true) {
let timer;
// 延迟执行函数
const later = (context, args) => setTimeout(() => {
timer = null;// 倒计时结束
if (!immediate) {
func.apply(context, args);
//执行回调
context = args = null;
}
}, wait);
let debounced = function (...params) {
let context = this;
let args = params;
if (!timer) {
timer = later(context, args);
if (immediate) {
//立即执行
func.apply(context, args);
}
} else {
clearTimeout(timer);
//函数在每个等待时延的结束被调用
timer = later(context, args);
}
}
debounced.cancel = function () {
clearTimeout(timer);
timer = null;
};
return debounced;
};
function handleClick(e) {
console.log(this); //this值正确传递
console.log(e, [...arguments].splice(1)); //参数正确传递
}
/* 防抖,immediate = ture 每个等待时延的开始被调用 */
let handle = debounce(handleClick, 1000, true);
// let handle = _.debounce(handleClick, 1000, {
// leading: true,
// trailing: false
// });
document.querySelector('.base').onclick = handle;
}
</script>