防抖函数实现
-
防抖作用:防止高频操作导致的函数频繁多次调用问题;
-
场景:页面滚动频繁触发scroll;窗口变化频繁触发resize;文本框输入频繁触发input事件;拖拽事件;键盘keypress事件...
-
应用:输入框连续输入值,只在最后一次输入完成才触发查询;点赞、表单提交等类似动作;
-
//lodash体验 <body> <div> <input type="text" oninput="handleInput(event)" /> </div> <script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.js"></script> <script type="text/javascript"> function input(e) { console.log(e.target.value) } let handleInput = _.debounce(input, 500, { leading: false, trailing: true, }) </script> </body> -
// 简单实现:lodash的options参数使用immediate代替 <body> <div> <input type="text" oninput="handleInput(event)" /> </div> <script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.js"></script> <script type="text/javascript"> /** * @param {function} func :传入debounce的执行函数 * @param {number} wait :允许函数调用的时间间隔 * @param {boolean} immediate :是否立即调用函数 */ function debounce(func, wait, immediate) { let timer, context, args let delay = () => setTimeout(() => { // timer清空放在定时器内部,保证最后一次执行后timer为null timer = null if (!immediate) { func.apply(context, args) context = args = null } }, wait) return function (...params) { if (!timer) { timer = delay() // 如果立即执行调用函数,否则缓存context和args if (immediate) { func.apply(this, params) } else { context = this args = params } } else { clearTimeout(timer) timer = delay() } } } function input(e) { console.log(e.target.value) } let handleInput = debounce(input, 500, false) </script> </body>

浙公网安备 33010602011771号