forked from YvetteLau/Blog
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththrottle.html
More file actions
99 lines (86 loc) · 2.87 KB
/
throttle.html
File metadata and controls
99 lines (86 loc) · 2.87 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<!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 throttle(func, wait, options) {
var timeout, context, args, result;
var previous = 0;
if (!options) options = {};
var later = function () {
previous = options.leading === false ? 0 : Date.now() || new Date().getTime();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
var throttled = function () {
var now = Date.now() || new Date().getTime();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
throttled.cancel = function () {
clearTimeout(timeout);
previous = 0;
timeout = context = args = null;
};
return throttled;
}
function a() {
console.log(1);
}
let b = throttle(a, 1000);
// let b = _.throttle(a, 2000);
// setTimeout(b, 0);
setTimeout(b, 500);
setTimeout(b, 1800);
setTimeout(b, 2200);
function handleClick(e) {
console.log(this); //this值正确传递
console.log(e, [...arguments].splice(1)); //参数正确传递
}
let handle = throttle(handleClick, 2000);
// let handle = _.throttle(handleClick, 2000);
document.querySelector('.base').onclick = handle;
}
</script>