js防抖
# demo1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>防抖优化</title>
</head>
<body>
请输入信息:<input type="text">
<script>
var processor = {
timeoutId: null,
performProcessing: function() {
var days = new Date()
var a= days.getHours();
var b= days.getMonth();
var c= days.getSeconds();
var d= days.getMilliseconds();
console.log(a+'时'+b+'分'+c+'秒'+d+'毫秒');
},
process: function() {
var that = this;
clearTimeout(that.timeoutId);
that .timeoutId = setTimeout(function() {
that.performProcessing();
}, 500) //每隔500毫秒后执行,如果中间间隔没到五秒钟还在输入,那么这500毫秒将重新开始计算
}
};
document.querySelector('input').oninput = function() {
processor.process();
}
</script>
</body>
</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
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
# demo2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div style="height: 3000px;background-color: aqua"></div>
<script>
//防抖debounce代码:
function debounce(fn,delay) {
var timeout = null; // 创建一个标记用来存放定时器的返回值
return function (e) {
// 每当用户输入的时候把前一个 setTimeout clear 掉
clearTimeout(timeout);
// 然后又创建一个新的 setTimeout, 这样就能保证interval 间隔内如果时间持续触发,就不会执行 fn 函数
timeout = setTimeout(() => {
fn.apply(this, arguments);
}, delay);
};
}
// 处理函数
function handle() {
console.log('防抖:', Math.random());
}
//滚动事件
window.addEventListener('scroll', debounce(handle,500));
</script>
</body>
</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
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
上次更新: 2022/05/12 14:57:53