如何实现防抖和节流?
防抖和节流是常见的前端性能优化方案
防抖:在触发频率高的事件中,执行耗费性能的操作,连续操作后只有最后一次生效
//自己实现debounce function debounce(func,wait=0){ let timeId //为什么不在内部声明id?因为我如果在内部声明,每一次触发事件就会有一个新的变量产生 return function(...args){ const self=this clearTimeout(timeId) timeId=setTimeout(()=>{ func.apply(self,args) },wait) } }
节流:在触发频率高的事件中,执行耗费性能操作,连续触发,单位时间内只有一次生效
function throttle(func,wait=0){ let timeId return function(...args){ const self=this setTimeout(()=>{ func.apply(self,args) timeId=undefind },wait) } } //-----------测试用例 function handleClick(){ console.log("click me",new Date().toLocaleTimeString()) } document.addEventListener('DOMContentLoaded',()=>{ const button = document.querySelector('#myButton')//html中定义个按钮 if(button){ const t=throttle(handleClick,3000) button.addEventListener('click',t) } }