相关信息
scroll 事件本身会触发页面的重新渲染,同时 scroll 事件的 handler 又会被高频度的触发, 因此事件的 handler 内部不应该有复杂操作,例如 DOM 操作就不应该放在事件处理中。
针对此类高频度触发事件问题(例如页面 scroll ,屏幕 resize,监听用户输入等),下面介绍两种常用的解决方法,防抖和节流。
// 函数防抖的实现 function debounce(fn, wait) { var timer = null; return function () { var context = this, args = arguments; // 如果此时存在定时器的话,则取消之前的定时器重新记时 if (timer) { clearTimeout(timer); timer = null; } // 设置定时器,使事件间隔指定事件后执行 timer = setTimeout(() => { fn.apply(context, args); }, wait); }; } // test var debounceRun = debounce(function () { console.log(123); }, 2000); // 只有当鼠标移动停止后2s打印123 window.addEventListener('mousemove', debounceRun);
// 函数节流的实现; function throttle(fn, delay) { var preTime = Date.now(); return function () { var nowTime = Date.now(); if (nowTime - preTime >= delay) { preTime = nowTime; fn.apply(this, arguments); } }; } // test var throttleRun = throttle(() => { console.log(123); }, 2000); // 不停的移动鼠标,控制台每隔2s就会打印123 window.addEventListener('mousemove', throttleRun);
本文作者:前端小毛
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!