JavaScript的防抖功能执行起来非常快。在定时器中上一个函数执行之前,下一个函数开始执行,导致之前的定时器任务被清除。//防抖(debounce)只能在一定时间内执行最后一次函数调用functiondebounce(fn,delay){lettimeout=null//初始化一个定时器returnfunction(...args){//当已经存在的定时器,则取消,类似于取消上次的setTimeout函数=setTimeout(()=>{fn(...args)},delay)}}constdebounceFn=debounce((a,b)=>console.log(a+b),2000)debounceFn(1,2)//canceleddebounceFn(2,3)//canceleddebounceFn(3,4)//canceleddebounceFn(4,5)//canceleddebounceFn(5,6)//11JavaScript节流函数//节流函数(throttle)传入的函数会在延迟时间内只执行一次functionthrottle(fn,delay){letstatus=true//定义一个状态值并初始化为truereturnfunction(...args){if(!status)return//当初始化值为真,我t表示有函数正在执行status=false//设置status值为false,防止其他函数执行setTimeout(()=>{fn(...args)status=true//函数执行后,状态值重置为true,此时可以执行下一个函数},delay)}}constthrottleFn=throttle((a,b)=>console.log(a+b),2000)throttleFn(1,2)//3throttleFn(1,2)//cancelledthrottleFn(1,2)//cancelledthrottleFn(1,2)//cancelledthrottleFn(1,2)//取消
