一、抖动是什么?
在事件被触发n秒后再执行回调函数,如果在这n秒内又被触发,则重新计时。
手写代码如下
// 防抖
function debounce(fn,time){
let timer=null//记录定时器
return function(){
if(timer){
clearTimeout(timer);//清空计时器
timer=null
}
timer = setTimeout(() => {
fn.apply(this,arguments)
//绑定的this是windows,是为了能调用fn函数
// fn()
}, time);
}
}
//调用debounce抖动函数
var debouncerun=debounce(function(){
console.log("123");//输出来证明抖动是否生效
},1000)
window.addEventListener('mousemove',debouncerun)//添加监听事件
二、截流
规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只有一次能生效。
代码如下(示例):
//截流
function throttle(fn,timer){
var time1=Date.now()//记录第一次时间
return function(){
var time2=Date.now()//记录后来的时间
if(time2-time1>=timer){
time1=time2
fn()
}
}
}
var throttles=throttle(()=>{
console.log("1111");
},1000)
window.addEventListener('mousemove',throttles)