防抖与节流

防抖:当持续触发事件时,会等到停止后一段时间才开始执行

应用场景:表单验证,按键提交

实现原理:利用setTimeout ,每次调用都会用clearTimeout清除前一次的定时器

代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function debounce(func, wait) {
var timeout;
return function () {
var context = this; //记录当前this
var arg=arguments; //记录当前参数
clearTimeout(timeout)
timeout = setTimeout(function(){
//经过匿名函数指向,this指向已经指向windows,所以早着需要修改this指向
func.apply(context,arg)
}, wait);
}
}
document.onwheel=debounce(function(){
console.log(11);
},1000)

节流:会每隔一段时间,才执行执行一次

应用场景:Dom拖拽,需要计算鼠标移动距离

实现原理:设定固定事件间隔,判断有没有超过时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function throttle(func, wait) {
var context, args;
var previous = 0;
return function() {
var now = +new Date();
context = this;
args = arguments;
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
// 时间没到,啥都不干
}
}
document.onwheel=throttle(function(){
console.log(11);
},1000)

防抖与节流
https://tian-1-2.github.io/typblog/2022/05/23/2022523-防抖与节流/
作者
田云鹏
发布于
2022年5月23日
许可协议