闭包可以完成的功能:1.防抖、2.节流、3.函数柯里化
1.防抖
//防抖 避免函数的重复调用 只会调用一次
function Antishake(fn,wait){ //第一个参数是函数 第二个参数是毫秒值
let timer = null //声明一个变量来接收延时器 初始值为null
return function(){
clearTimeout(timer)
timer = setTimeout(() => {
fn() //调用这函数
}, wait);
}
}
let an = Antishake(function(){ //用一个变量接收
console.log('555');
},2000)
document.querySelector('div').onmouseenter = ()=>{
an() //调用一次
}
2.节流
function throttle(fn,wait){
let timer = null //节点闸
return function(){
if(timer) return //null false 不是null结果减少true 如果上传没有我就直接跳过 没有人我就上去
timer = setTimeout(() => { //上车了
fn()
timer = null //做完之后重新关闭节点闸
}, wait);
}
}
let throttle1 = throttle(()=>{
console.log('我上车了');
},2000)
document.querySelector('div').onclick = ()=>{
throttle1()
}