函数节流(throttle)

1. 什么是函数节流(throttle)

函数节流(throttle)概念:规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次只有一次能生效。

2. 生活中的例子

当 1 秒内连续播放 24 张以上的图片时,在人眼的视觉中就会形成一个连贯的动画,所以在电影的播放中大概是以每秒 24 张的速度播放的,为什么不是 100 张或更多呢?其原因是因为 24 张就可以满足人类视觉需求的时候,100 张就会显得很浪费资源

3. 函数节流的应用场景

  1. 游戏中的刷新率;
  2. DOM元素拖拽;
  3. Canvas画笔功能。

总的来说,适合大量事件按时间做平均分配触发。

4. 函数节流的代码

和上一次分享的函数防抖实现的效果类似,每1s在浏览器上输入x轴的数值,并且在这1s内只触发一次事件。下面的代码分为一个先显示一个后显示。

先显示的代码如下所示:

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
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>防抖节流</title>
<style>
#container{
height: 200px;
width: 100%;
background: rebeccapurple;
text-align: center;
font-size: 30px;
color: #fff;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
// 节流 方法一 用的now来实现的 先执行
const container = document.getElementById("container");
function throttle(fn,wait){
let pre = 0;
return function(event){
let now = Date.now();
let _this = this;
if(now - pre > wait){
fn.apply(_this,[event]);
pre = now;
}
}
}
function sum(e){
this.innerHTML = e.clientX;
}
container.onmousemove = throttle(sum,1000);
</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
36
37
38
39
40
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>防抖节流</title>
<style>
#container{
height: 200px;
width: 100%;
background: rebeccapurple;
text-align: center;
font-size: 30px;
color: #fff;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
// 方法二 开一个计时器 后执行
const container = document.getElementById("container");
function throttle(fn,wait){
let timer;
return function(event){
let _this = this;
if(!timer){
timer = setTimeout(function(){
fn.apply(_this,[event]);
timer = null;
},wait);
}
}
}
function sum(e){
this.innerHTML = e.clientX;
}
container.onmousemove = throttle(sum,1000);
</script>
</body>
</html>