1.防抖
1.1 概念
防抖策略(debounce)是当事件被触发后,延迟n秒后再执行回调,如果在这n秒内事件又被触发,则重新计时。
作用: 高频率触发的事件,在指定的单位时间内,只响应最后一次,如果在指定的时间内再次触发,则重新计算时间。
1.2 应用场景
- 登录、发短信等按钮避免用户点击太快,以致于发送了多次请求,需要防抖
- 调整浏览器窗口大小时,resize 次数过于频繁,造成计算过多,此时需要一次到位,就用到了防抖
- 文本编辑器实时保存,当无任何更改操作一秒后进行保存
1.3 实现思路

1.4 具体实现
function myDebounce(func, wait) {
let timeout=null;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function() {
func.apply(context, args);
}, wait);
};
}
测试一下代码:
<head>
<meta charset="UTF-8" />
<title>Title</title>
<style>
.box {
width: 120px;
height: 120px;
background-color: aqua;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
let box = document.querySelector(".box");
let i = 0;
function myDebounce(func, wait) {
let timeout = null;
return function () {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function () {
func.apply(context, args);
}, wait);
};
}
box.addEventListener(
"mousemove",
myDebounce(function (content) {
box.innerHTML = i++;
console.log(content);
}, 500)
);
</script>
</body>
2.节流
2.1 概念
n 秒内只运行一次,若在 n 秒内重复触发,只有一次生效。
作用: 高频率触发的事件,在指定的单位时间内,只响应第一次。
2.2 应用场景
- 鼠标连续不断地触发某事件(如点击),单位时间内只触发一次;
- 监听滚动事件,比如是否滑到底部自动加载更多,用throttle来判断。例如:懒加载;
- 浏览器播放事件,每个一秒计算一次进度信息等
- 表格框选
2.3 实现思路

2.4 具体实现
function myThrottle(fn, time) {
let timer = null;
return function () {
let context = this;
let args = arguments;
if (!timer) {
fn.apply(context, args);
timer = setTimeout(function () {
timer = null;
}, time);
}
};
}
测试一下:
<head>
<meta charset="UTF-8" />
<title>Title</title>
<style>
.box {
width: 120px;
height: 120px;
background-color: aqua;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
let box = document.querySelector(".box");
let i = 0;
function mouseMove() {
box.innerHTML = i++;
}
function myThrottle(fn, time) {
let timer = null;
return function () {
let context = this;
let args = arguments;
if (!timer) {
fn.apply(context, args);
timer = setTimeout(function () {
timer = null;
}, time);
}
};
}
box.addEventListener(
"mousemove",
myThrottle(function (content) {
console.log(content);
}, 500)
);
</script>
</body>

1200

被折叠的 条评论
为什么被折叠?



