节流(throttle): 指连续触发事件的函数,在一定时间间隔内只执行一次。 function throttle(fn, delay) { let timer = null; return function() { const self = this; const args = arguments; if (!timer) { timer = setTimeout(function() { timer = null; fn.apply(self, args); }, delay) } } } //使用 window.addEventListener('scroll', throttle(function() { console.log('scroll') }, 1000)) 防抖(debounce): 如果在一定时间内再次触发,就会取消上一的操作,重新执行最新的操作。 function debounce(fn, delay) { let timer = null; return function() { const self = this; const args = arguments; if (timer) { clearTimeout(timer) } timer = setTimeout(function() { fn.apply(self, args); }, delay) } } //使用 window.addEventListener('input', debounce(function() { console.log('input') }, 1000))
标签:function,防抖,const,节流,self,args,timer,js,delay From: https://www.cnblogs.com/cnwp007/p/17354716.html