- 执行函数
function doSth(sth){
console.log(sth)
}
- 防抖
function debounce(fn,wait){
let timer
return (...args)=>{
clearTimeout(timer)
timer = setTimeout(()=>{
fn.apply(this,args)
},wait)
}
}
-
节流时间戳版
function throttle(fn, delay) {
let last
return (...args) => {
let now = +new Date()
if (!last || now >= last + delay) {
last = now
fn.apply(this,args)
}
}
}
- 节流定时器版
function throttle(fn,wait){
let timer
return (...args)=>{
if(!timer){
timer = setTimeout(()=>{
fn.apply(this,args)
clearTimeout(timer)
},wait)
}
}
}
注:无法确定返回函数在何处调用,所以执行fn函数时对其进行绑定this指向