防抖
-
事件被执行n秒后,再执行回调,如果n秒内又触发了,则从新计时
function debounce(fn, delay) { let timer = null; return function(){ cleatTimeout(timer); const self = this; const args = arguments; timer = setTimeout(() => { fn.apply(self, args); }, delay) } }
节流
-
每隔一段时间,执行一次
function throttled(fn, delay) { const startTime = Date.now(); let timer = null; return function(){ const self = this; const args = arguments; clearTimeout(timer); let currentTime = Date.now(); const remaining = delay - (currentTime - startTime); if(remaining < 0) { fn.apply(self, args); currentTime = Date.now(); }else { timer = setTimeout(fn, delay) } } }
发表回复