节流:
闭包添加一个上下文的变量来实现。
function throttle(func, wait) {
let previous = 0;
return function() {
let now = Date.now();
let context = this;
let args = arguments;
if (now - previous > wait) {
func();
previous = now;
}
}
}
防抖:
function debounce(fn , wait){
let timer = null
let flag = true
return function(){
if(timer){
clearTimeout(timer)
}
if(flag){
fn()
}
flag = false
timer = setTimeout(()=>{
fn.apply();
flag=true
},wait)
}
}