1. 防抖
防抖=》固定的时间内,事件只允许发生一次
// 防抖封装
//func 是事件处理程序,delay 是事件执行的延迟时间,单位:毫秒
function debounce(func, delay){
var timer = null;
return function(){
var that = this;
var args = arguments
//每次触发事件 都把定时器清掉重新计时
clearTimeout(timer)
timer = setTimeout(function(){
//执行事件处理程序
func.call(that, args)
}, delay)
}
}
2. 节流
节流=》一定时间内多个事件合成一个
应用场景=》1. 提交表单 2. 高频监听事件
1)、通过定时间器节流
//event是事件处理程序,time是事件执行的延迟时间,单位:毫秒
function throttle(event,time){
let timer=null
return function(){
if(!timer){
timer=setTimeout(()=>{
event();
timer=null;
},time)
}
}
}
2)、通过时间戳 节流
//func 是事件处理程序,delay 是事件执行的延迟时间,单位:毫秒
function throttle(func, delay){
//定义初始时间(开始触发事件的时间)
var start = 0;
return function(){
var that = this;
var args = arguments;
//获取当前时间戳
var current = Date.now();
// 判断当前时间与初始时间是否超过间隔
if(current - start >= delay){
//执行事件处理程序
func.call(that, args)
//更新初始时间
start = current;
}
}
}