-
Notifications
You must be signed in to change notification settings - Fork 96
/
Throttle and debounce.html
96 lines (82 loc) · 2.34 KB
/
Throttle and 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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>节流与防抖</title>
<style>
body {
min-height: 3000px;
width: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="main">
<p>函数节流是指一定时间内js方法只跑一次。就像技能cd,你再怎么摁一段时间只能触发一次。这是函数节流最形象的解释。</p>
<p>函数防抖是指频繁触发的情况下,只有足够的空闲时间,才执行代码一次。比如生活中的坐公交,就是一定时间内,如果有人陆续刷卡上车,司机就不会开车。只有别人没刷卡了,司机才开车。</p>
<p>滚动滚轮感受节流</p>
</div>
<script> //节流
//主要思想是设置一个守卫,如果settimeout已经执行过了(在等待回调了),就不会创建新的settimeout
var count = 0,
main = document.getElementById('main');
var scrollFun = function(time) {
var canRun = true;
return function() {
if(canRun) {
canRun = false;
setTimeout(() => {
main.innerHTML += "<p>第" + ++count + "行</p>";
console.log("发生了!");
canRun = true;
}, time);
}
};
}
window.onscroll = scrollFun(300);
// 节流函数
function throttle(fn, gapTime) {
let _lastTime = null;
return function () {
let _nowTime = + new Date()
if (_nowTime - _lastTime > gapTime || !_lastTime) {
fn();
_lastTime = _nowTime
}
}
}
// 触发
let fn = ()=>{
console.log('boom')
}
setInterval(throttle(fn,1000),10)
</script>
<!-- <script> //防抖
//主要思想是如果频繁触发就取消上一个,重新创建一个规定时长的settimeout
var count = 0,
main = document.getElementById('main');
var debounce = function(time) {
var setTimeId = null;
return function() {
clearTimeout(setTimeId);
setTimeId = setTimeout(() => {
main.innerHTML += "<p>第" + ++count + "行</p>";
console.log("发生了!");
}, time);
}
}
window.onscroll = debounce(30);
//防抖函数
const debounce = (fn, time) => {
let timerId;
return function(...args) {
const functionCall = () => fn.apply(this, args);
clearTimeout(timerId);
timerId = setTimeout(functionCall, time);
};
};
</script> -->
</body>
</html>