函数防抖 debounce
希望函数只执行一次,哪怕我进行了多次调用
01 无论触发多少次只执行最后一次
let box = document.querySelector("#box");
let index = 0;
let timer=0;
box.onmousemove=function(){
index++;
clearTimeout(timer);
timer=setTimeout(()=>{
console.log("move",index);
},200)
};
02 无论触发多少次只执行第一次
let box = document.querySelector("#box");
let index = 0;
let timer=0;
let isEnd=true;
box.onmousemove=function(){
index++;
clearTimeout(timer);
isEnd&&(console.log("move",index))
isEnd=false;
timer=setTimeout(()=>{
isEnd=true;
},200)
}
03 封装防抖函数
function debounce(fn,delay=200,isStart=false){
let timer=0;
let isEnd=true;
return function(...args){
const _this=this;
if(isStart){
isEnd&&fn.apply(_this,args);
isEnd=false;
}
timer=setTimeout(()=>{
(!isStart)&&fn.apply(_this,args);
isEnd=true;
},delay)
}