防抖节流

防抖:

**事件触发过于频繁,只要最后的一次来执行事件 **;

例如input标签存在 输入内容后提示

一般每输入一个字符就会oninput事件

防抖动会让内容交互的次数较少在最后提交

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
<!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>Document</title>
</head>
<body>
<!--
事件触发过于频繁,只要最后的一次来执行事件
例如input标签存在 输入内容后提示
一般每输入一个字符就会oninput事件
防抖动会让内容交互的次数较少在最后提交
-->
<input type="text">
<script>
let inp = document.querySelector("input")
inp.oninput = antiShake(function(){
console.log(this.value);
},500)
function antiShake(fn,delay){
let t = null;
return function(){
if(t){
clearTimeout(t);
}
t = setTimeout(()=>{
fn.call(this)
},delay)
}
}

</script>
</body>
</html>

这样再每隔0.5秒的时候才会从input提交内容,来显示,避免了oninput事件触发过于频繁

节流

控制高频事件的执行次数

例如页面滚动事件

代码与防抖类似。

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
<!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>Document</title>
<style>
body{
height: 2000px;
}
</style>
</head>
<body>
<!--
控制高频事件的执行次数
例如页面滚动事件

-->
<script>
// 触发过于频繁
// window.onscroll = function(){
// console.log(1)
// }

// 添加节流事件,并用闭包
window.onscroll = throttle(function(){
console.log('1')
},500)

function throttle(fn,delay){
let t = true;
return function(){
if(t){
setTimeout(()=>{
fn();
t = true;
},delay)
}
t = false

}
}

</script>
</body>
</html>