防抖
非立即执行:
function Debounce(fn,wait,...args){
let timeout;
return function(){
const that=this;
if(timeout) clearTimeout(timeout);
timeout=setTimeout(()=>{
fn.apply(that,args)
},wait)
}
}
立即执行:
function Debounce(fn,wait,...args){
let timeout;
return function(){
const that=this;
if(timeout) clearTimeout(timeout);
let exe=!timeout;
timeout=setTimeout(()=>{
timeout=null;
},wait)
if(exe) fn.apply(that,args)
}
}
节流:
时间戳版:
function throttle(fn,wait,...args){
let pre=0;
return function(){
const that=this;
let nowTime=Date.now()
if(nowTime-pre>=wait){
fn.apply(that,this);
pre=Date.now()
}
}
}
定时器版:
function throttle(fn,wait,...args){
let timeout;
return function(){
const that=this;
if(!timeout){
timeout=setTimeout(()=>{
timeout=null;
fn.apply(that,args)
},wait)
}
}
}
防抖和节流
最新推荐文章于 2023-10-16 16:32:46 发布